3

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
user7190476
  • 35
  • 1
  • 1
  • 7
  • 1
    Here we go again. You get back an observable of response, and not the response itself, because an HTTP call is **asynchronous**. Once you have called HttpClient and subscribed, you have only **sent** the request. The response will come back much later, and at that point, the callback passed to subscribe will be executed. So, of course the response is undefined right after you're just sent the request. Put your console.log() **inside** the subscribe callback. – JB Nizet Jul 08 '18 at 08:54
  • 1
    Possible duplicate of [Angular HttpClient data undefined out of subscribe](https://stackoverflow.com/questions/47284763/angular-httpclient-data-undefined-out-of-subscribe) – JB Nizet Jul 08 '18 at 08:57

1 Answers1

4

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 => {

  });
ElasticCode
  • 7,311
  • 2
  • 34
  • 45
  • 1
    Yeah, did that. Tried to alert this.config, but it stays undefined. So my problem is, how in earth I get the response value assigned to this.config? And use it out of subscribe-function – user7190476 Jul 08 '18 at 09:05
  • Maybe, yet still the problem is how can I use that data outside subscribe? Because this.config is still undefined outside. EDIT. Got it working, it shows on view and can be fired with button with a right output :). Thanks! – user7190476 Jul 08 '18 at 09:18
  • You can call it after `ngOnInit()` is done. In any other action, like button click. – ElasticCode Jul 08 '18 at 09:24
  • Yeah, now I kinda understand how this goes :). Thanks! – user7190476 Jul 08 '18 at 09:28