Encountered an issue in Angular 2 when the property 'then' was not found on type 'Subscription'

I have been attempting to call a service from my login.ts file but I am encountering various errors. Here is the code snippet in question:

login.ts

import { Component } from '@angular/core';
import { Auth, User } from '@ionic/cloud-angular';
import { NavController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { TabsPage } from '../tabs/tabs';
import { AuthService } from '../../services/auth/auth.service';
import { Observable } from 'rxjs/Rx';


@Component({
  templateUrl: 'login.html'
})

export class LoginPage {
    authType: string = "login";
    error: string;
    storage: Storage = new Storage();

  constructor(public auth: Auth, public user: User, public navCtrl: NavController, public authService: AuthService) {}

  facebookLogin() {
    this.auth.login('facebook').then((success) => {
        this.authService.signup(this.user.social.facebook).then((success) => {

        });
    });

  }
}

auth.service.ts

import { Storage } from '@ionic/storage';
import { AuthHttp, JwtHelper, tokenNotExpired } from 'angular2-jwt';
import { Injectable, NgZone } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { Http, Headers } from 'angular2/http';

@Injectable()
export class AuthService {

  jwtHelper: JwtHelper = new JwtHelper();
  // contentHeader = new Headers({"Content-Type": "application/json"});
  storage: Storage = new Storage();
  refreshSubscription: any;
  user: Object;
  zoneImpl: NgZone;
  idToken: string;
  error: string;

  constructor(private authHttp: AuthHttp, zone: NgZone) {
    this.zoneImpl = zone;
    // Check if there is a profile saved in local storage
    this.storage.get('profile').then(profile => {
      this.user = JSON.parse(profile);
    }).catch(error => {
      console.log(error);
    });

    this.storage.get('id_token').then(token => {
      this.idToken = token;
    });
  }

  public authenticated() {
    return tokenNotExpired('id_token', this.idToken);
  }

  public signup(params) {
    var url = 'http://127:0.0.1:3000/api/v1/register';
    return this.authHttp.post(url, JSON.stringify(params))
        .map(res => res.json())
        .subscribe(
          data => {this.storage.set('id_token', data.token)},
          err => this.error = err
        );
  }
}

Essentially, what I aim to achieve is for the facebookLogin() function to trigger the singup() method within auth.service.ts. However, I am consistently receiving the error message:

Property 'then' does not exist on type 'Subscription'
.

Can anyone provide insight into what this error signifies and offer guidance on how to rectify it?

Answer №1

Make the change from using subscribe to toPromise() (remember to import toPromise)

  public signup(params) {
    var url = 'http://127:0.0.1:3000/api/v1/register';
    return this.authHttp.post(url, JSON.stringify(params))
        .map(res => res.json())
        .toPromise(
          data => {this.storage.set('id_token', data.token)},
        );
  }

Alternatively, switch to using .map() and replace then() with subscribe() at the calling location.

 public signup(params) {
    var url = 'http://127:0.0.1:3000/api/v1/register';
    return this.authHttp.post(url, JSON.stringify(params))
        .map(res => {
          let data = res.json();
          this.storage.set('id_token', data.token);
          return data;
        });
  }
  facebookLogin() {
    this.auth.login('facebook').then((success) => {
        this.authService.signup(this.user.social.facebook).subscribe((success) => {

        });
    });

  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does the data appear differently in Angular 9 compared to before?

In this particular scenario, the initial expression {{ bar }} remains static, whereas the subsequent expression {{ "" + bar }} undergoes updates: For example: two 1588950994873 The question arises: why does this differentiation exist? import { Com ...

Using TypeScript to Declare Third Party Modules in Quasar

I'm currently trying to integrate Dropzone-vue into my Quasar project. However, I've encountered an issue as I can't directly install and declare it in a main.js file due to the lack of one in Quasar's structure. Additionally, an error ...

Implementation of multiple angular guards causing a crash on the page

I have been attempting to implement separate guards for distinct pages. Essentially, I am checking a boolean parameter to determine if a user is logged in or not. Below are the two guard.ts codes that I am using: export class IsAuthenticatedGuard implemen ...

Passing a value from an HTML template to a method within an Angular 4 component

Encountering an issue with Angular 4. HTML template markup includes a button: <td><a class="btn btn-danger" (click)="delete()"><i class="fa fa-trash"></i></a></td> Data is assigned to each td from a *ngFor, like {{ da ...

Problem displaying images in Mean stack app using CSS background-image and Webpack

Currently, I am enhancing my skills by working on my own projects. One of the projects I'm focused on right now is designing a MEAN-stack app that utilizes Webpack. In the past, I encountered an issue where I couldn't display images in my app. Ho ...

Advantages of using index.js within a component directory

It seems to be a common practice to have an index file in the component/container/module folders of react or angular2 projects. Examples of this can be seen in: angular2-webpack-starter react-boilerplate What advantages does this bring? When is it recom ...

"Guidance on setting up my input text box in Angular to allow for selection of required fields

I'm currently in the process of developing a form where all fields are required. My goal is to have the Next button move on to the subsequent form only if all required fields have been filled out. However, I seem to be encountering an issue where desp ...

Issue with dependency injection in Angular 16 when used as a standalone feature

Here are my standalone API calls within the service: import { Injectable} from '@angular/core'; import { ProductEndPoints } from '../../constants/apiConstants/product-endpoints'; import { HttpClient} from '@angular/common/http&ap ...

Exploring the possibilities of TypeScript/angularJS in HTTP GET requests

I am a beginner in typescript and angular.js, and I am facing difficulties with an http get request. I rely on DefinitelyTyped for angular's type definitions. This is what my controller code looks like: module game.Controller { 'use strict& ...

Brand new Angular 9 application encountering the error message "ERROR in Cannot read property 'flags' of undefined" when running "ng build" on a Mac device

I set up a fresh Angular 9 project on my MacBook by executing ng new demo (no routing, CSS) cd demo ng build However, I encountered the following error: ERROR in Cannot read property 'flags' of undefined When running "ng version", here's ...

The TypeScript reflection system is unable to deduce the GraphQL type in this case. To resolve this issue, it is necessary to explicitly specify the type for the 'id' property of the 'Address'

import { ObjectType, ID, Int, Field } from 'type-graphql'; @ObjectType() export default class Address { @Field(type => ID) id: String; @Field() type: string; @Field() title: string; @Field() location: string; } More informa ...

Is there a way to expand the return type of a parent class's methods using an object

Currently, I am enhancing a class by adding a serialize method. My goal is for this new method to perform the same functionality as its parent class but with some additional keys added. export declare class Parent { serialize(): { x: number; ...

Converting a unix timestamp to a Date in TypeScript - a comprehensive guide

To retrieve the unix timestamp of a Date in plain JavaScript and TypeScript, we can use this code snippet: let currentDate = new Date(); const unixTime = currentDate.valueOf(); Converting the unix timestamp back to a Date object in JavaScript is straight ...

What is the best way to set one property to be the same as another in Angular?

In my project, I have defined a class called MyClass which I later utilize in an Angular component. export class MyClass { prop: string; constructor(val){ this.prop = val; } public getLength(str: string): number { return str.length; } ...

Loop through a collection of elements of a certain kind and selectively transfer only certain items to a different collection of a different kind

When working with typescript, I am faced with the challenge of dealing with two arrays: interface IFirst{ name: string; age: number } interface ISecond { nickName: string; lastName: string; } myFirstArray: IFirst[]; mySecondArray: ISe ...

When accessing from the frontend (Angular), the User.FindFirst(ClaimTypes.NameIdentifier) method does not return any values

I'm encountering a new issue - just as the title suggests. I've managed to identify where the problem occurs but I'm unable to resolve it. Let's start from the beginning. In the backend (ASP.NET 3.0), I have a class AuthController with ...

What is the process of combining two states in Angular?

Having a state defined as: export interface ChatMessagesState { messages: Message[] | null; chatId: string; } and receiving data in the websocket like: newMessages: Message[] = [ { text: 'Hello', chatId: '100' }, { text ...

Guide on associating user IDs with user objects

I am currently working on adding a "pin this profile" functionality to my website. I have successfully gathered an array of user IDs for the profiles I want to pin, but I am facing difficulties with pushing these IDs to the top of the list of profiles. My ...

Basic cordova application that transfers data from one page to another using typescript

Currently, I am developing an Apache Cordova application using TypeScript. However, I am facing a challenge in passing information from one HTML page to another using TypeScript. I would appreciate it if someone could guide me on the steps needed for nav ...

Retrieving a variable value set within a jQuery function from within an Angular 2 component

In the current project, I am facing a situation where I need to work around and initialize jQuery datetimepicker inside an Angular 2 application (with plans to refactor it later). However, when I assign a datetime value to a variable, I encounter a proble ...