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

Tips for overlaying text on an image in html with the ability to zoom in/out and adjust resolution

My challenge is aligning text over an image so that they move together when zooming in or out. However, I am facing difficulties as the text and image seem to move in different directions. I have attempted using media queries and adjusting the positions of ...

What is the best way to combine the attributes of multiple objects within a union type?

I have a clearly defined schema type Schema = { a: { a: 1 } b: { b: 2 } } I am in need of a function that can generate objects that adhere to multiple schemas. function createObject<K extends keyof Schema>(schema: Array<K>, obj: Sche ...

Is it possible to eliminate a parameter when the generic type 'T' is equal to 'void'?

In the code snippet below, I am attempting to specify the type of the resolve callback. Initially: Generic Approach export interface PromiseHandler<T> { resolve: (result: T) => void // <----- My query is about this line reject: (error: a ...

When utilizing the Angular 9 package manager to install a package with the caret (^) in the package.json file, it may

Within my package.json file, I have specified the dependency "@servicestack/client":"^1.0.31". Currently, the most updated version of servicestack is 1.0.48. On running npm install on my local environment, it consistently installs vers ...

What causes typescript to trigger compilation errors in react-scripts when using certain keywords?

Struggling with a bizarre issue involving TypeScript and React Scripts Line 5:16: Parsing error: Unexpected token 3 | class AutoUpdateBase<TBinding> implements IAutoUpdate<TBinding>{ 4 | > 5 | protected binding?: (arg: TBinding) ...

The rxjs package is failing to meet the peerDependencies requirements of its sister packages

After running npm install, I came across this error: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "c:\\Program Files\\nodejs\\node.exe" "c:\\Program Files\\nodejs\\node_modules\\npm\ ...

At what point do we employ providers within Angular 2?

In the Angular 2 documentation, they provide examples that also use HTTP for communication. import { HTTP_PROVIDERS } from '@angular/http'; import { HeroService } from './hero.service'; @Component({ selector: 'my-toh&ap ...

Can we limit the return type of arrow function parameters in TypeScript?

Within my typescript code, there is a function that takes in two parameters: a configuration object and a function: function executeMaybe<Input, Output> ( config: { percent: number }, fn: (i: Input) => Output ): (i: Input) => Output | &apos ...

An error occurred during runtime while attempting to resolve all parameters for the UserService

I recently started using Ionic and I am trying to set up a sidebar with a user profile header, displaying the user's details as seen in other similar apps depending on who is logged in. Unfortunately, I have come across the following error: Runtime ...

Incorporating onPause and onResume functionalities into a YouTube video featured on a page built with Ionic 2

I'm encountering a minor problem with a simple demo Android app built in Ionic 2. Whenever a Youtube video is playing on the Homepage, if the power button is pressed or the phone goes into sleep/lock mode, the Youtube video continues to play. This is ...

Creating a factory function through typhography

I have a dynamically generated list of functions that take an argument and return different values: actions: [ param => ({name: param, value: 2}), param => ({label: param, quantity: 4}), ] Now I am looking to create a function that will gen ...

Angular 2: A ready-made solution for developing interactive discussion features

Currently working on my Angular 2 application and looking to incorporate a discussion feature. Are there any pre-existing solutions available for this integration? ...

Send the index of the row to the event handler in the table of data

I am currently utilizing a data table component from PrimeNG and have the following template code: <p-column [style]="{'width':'40px'}"> <template let-col let-rowData="rowData" let-rowIndex="rowIndex" pTemplate type="body" ...

Retrieve the text content of the <ul> <li> elements following a click on them

Currently, I am able to pass the .innerTXT of any item I click in my list of items. However, when I click on a nested item like statistics -> tests, I want to display the entire path and not just 'tests'. Can someone assist me in resolving thi ...

Experience the magic of live streaming with our cutting-edge technology bundle featuring RTSP streaming, AspNet 5 API integration, FFM

Description: I am working on an API (ASP.Net 5) that connects to an IP Camera through RTSP. The camera sends a h264 stream converted with ffmpeg as an m3u8 stream, which is then returned to the Angular client in the following manner: public async Task< ...

Issues with eventEmitter functionality in Angular 2

Everyone performed admirably following the manual, here is the code snippet for WebSocketBroadcaster: import {EventEmitter, Injectable} from "@angular/core"; @Injectable() export class WebSocketBroadcaster { ee: EventEmitter<any> = new EventEmi ...

Slice an interactive div

I am currently working on setting up a horizontal sliding div for a menu. The layout consists of a left DIV that remains visible at all times, and a sliding DIV that appears horizontally when the menu is activated. My HTML code looks like this. <div id ...

"Exploring the possibilities of Angular 6 through custom pipe

Is there a way to integrate a custom pipe from an Angular 6 library into my main app? I have been attempting to do so in the following manner: @NgModule({ declarations: [ SomePipe ], exports: [ SomePipe ]}) Within public_api.ts: export * fr ...

When using `JSON.stringify`, the resulting data may vary from the original object

Here is the code snippet in question: console.log("444444: ", profile, JSON.stringify(profile)) Upon checking the log output: https://i.stack.imgur.com/LzalV.png I am trying to understand why I cannot see the value: [0] present Additionally, ...

Press the damaged interior when looping through array elements in *ngFor, especially if they are generated from a function

When working with Plnkr, I encountered a peculiar edge case that seems to be related to the usage of pixijs or webgl. Interestingly, clicking on elements in the list works fine until you interact with pixijs by clicking the button, after which the click ev ...