Search code examples
angularresponsesubscribe

Angular subscribe response


Okay, I'm pretty new to Angular, so I have this little problem. So i'm following the Angular guide (https://angular.io/guide/http). So my problem is that my http-response is always undefined. In debug-tools the response is:

{"code":0,"status":"error","message":"Invalid JWT - Authentication failed!"}

as it should be. But when I console-log response, it always says

This should be the response???:  undefined

profile.component.ts

import { Component, OnInit } from '@angular/core';
import { parse } from 'path';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { getLocaleTimeFormat } from '@angular/common';
import { UserService } from '../user.service';
import { Config } from '../config';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})

export class ProfileComponent implements OnInit {

  tmp: any;
  token: any;
  tmp2: any;
  config: Config;
  constructor(private userService: UserService, private router: Router,
    private http: HttpClient) { }

  ngOnInit() {


    this.token = localStorage.getItem('token');
    this.tmp = this.userService.checkToken(this.token)
      .subscribe((data: Config) => this.config = {
        code: data['code'],
        message: data['message']
      });

    console.log("This should be the response???: ", this.config);
  }

}

and the user.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Response } from "@angular/http";
import { Observable } from "rxjs";
import 'rxjs/add/operator/map';
import { httpFactory } from '@angular/http/src/http_module';
import { Config } from './config';

@Injectable({
  providedIn: 'root'
})
export class UserService {


  config: Config;
  items: any;
  readonly url = 'http://localhost:82/phpangular/userSystem/src/api/userCtrl.php';


  constructor(private http: HttpClient, private router: Router) { }

  checkToken(token) {
   return this.http.post<Config>
   (this.url, {'data': 'checkToken', 'token': token});
  }


}

and my interface config.ts

export interface Config {

    code: string;
    message: string;
}

If someone would give me a pointer, I would be real glad :)

Cheers

  • Niko

Solution

  • Your console.log should be inside subscribe callback

    this.tmp = this.userService.checkToken(this.token).subscribe(
      data => {
        this.config = <Config>(data);
        console.log("This should be the response???: ", this.config);
      },
      err => {
    
      });