如何访问angular5 httpclient答案?

时间:2017-12-03 15:01:22

标签: httpclient angular5

export class AppComponent实现OnInit {

userObservable:any = {};

构造函数(私有httpClient:HttpClient){}

ngOnInit():void {

this.httpClient.get<UserResponse>("http://localhost:9000/home")
    .subscribe(data  => {console.log(data.status);
                         console.log(data.password);
                         this.userObservable = data;
                         console.log('Result ==> ',this.userObservable);
                        },
               error => {}
);
console.log(this.userObservable);

}

执行最后一个控制台语句时,显示的值为null。我需要在我的应用程序的其他组件中操作httpclient答案。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

这是因为你的最后一个console.log()语句在得到你的http答案之前就开始了。我建议使用服务:

export class AppComponent implements OnInit {
  constructor(private userService: UserService) {}

  ngOnInit(): void {
    this.userService.getUserData().subscribe(data => {
      console.log("Data :", data, "Data from service :", this.userService.userObservable);
      // DO OTHER STUFF
    });
  }


}

// Service
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
@Injectable()
  export class UserService {
     userObservable: any = {};

    constructor(private httpClient: HttpClient) {}

    getUserData() {
    this.httpClient.get<UserResponse>("http://localhost:9000/home").subscribe(
      data => {
        this.userObservable = data;
        console.log("Result ==> ", this.userObservable);
        return data;
      },
      error => {
        return error;
      }
    );
  }
}

您将能够使用该服务在每个组件中获取您的userData。