Angular订阅响应

时间:2018-07-08 08:50:38

标签: angular response subscribe

好的,我对Angular还是很陌生,所以我有这个小问题。因此,我正在遵循Angular指南(https://angular.io/guide/http)。所以我的问题是我的http响应始终是未定义的。在debug-tools中,响应为:

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

应当如此。但是,当我在控制台日志响应中时,它总是说

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);
  }

}

和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});
  }


}

和我的界面config.ts

export interface Config {

    code: string;
    message: string;
}

如果有人给我指点,我将非常高兴:)

欢呼

  • Niko

1 个答案:

答案 0 :(得分:2)

您的console.log应该在subscribe回调内部

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

  });