将订阅的值分配给变量时,我得到的是未定义的值。 这是我的代码。
service.ts
getIpAddress() : Observable<any>
{
return this.http
.get(this.Geo_Api)
.map((response: Response) => { return <any>response.json()
} )
.catch(this.handleError);
}
component.ts
constructor(private apiservice: ApiService )
{
this.getIpAddress();
}
ngOnInit() { console.log(this.client_ip$); }
getIpAddress()
{
this.apiservice.getIpAddress()
.subscribe(data => {
this.client_data$ = data.ip;
this.client_ip$ = this.client_data$;
});
}
答案 0 :(得分:1)
您必须先将其注入组件才能使用该服务。
constructor(private apiservice: Apiservice)
答案 1 :(得分:0)
constructor(private apiservice: ApiService )
{
}
ngOnInit() { this.getIpAddress(); } // call service in ngOnInit();
getIpAddress()
{
this.apiservice.getIpAddress()
.subscribe(data => {
this.client_data$ = data.ip;
this.client_ip$ = this.client_data$;
// as service is async call try console in subscirbe callback
this.useClient()
});
}
useClient(){
console.log(this.client_ip$);
}