[英]subscribe value undefined outside when assign to a variable in angular 5
I am getting undefined value when assigning the subscribed value to a variable. 将订阅的值分配给变量时,我得到未定义的值。 Here is my code.
这是我的代码。
service.ts service.ts
getIpAddress() : Observable<any>
{
return this.http
.get(this.Geo_Api)
.map((response: Response) => { return <any>response.json()
} )
.catch(this.handleError);
}
component.ts 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$;
});
}
您必须先将服务注入组件才能使用该服务。
constructor(private apiservice: Apiservice)
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$);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.