简体   繁体   中英

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

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

  }

您必须先将服务注入组件才能使用该服务。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM