簡體   English   中英

Angular2 - 將 http.get 響應傳遞給類對象

[英]Angular2 - Pass http.get response to class object

我是角度的新手。 我有一個 json 文件,我可以在其中配置我需要在我的應用程序中使用的 url。

應用程序/配置/development.json

{
   "apiUrl": "http://staging.domain.com:9000/",
   "debugging": true
}

下面是我在 config.service.ts 中的代碼:

export class ConfigService {
    private apiURL:any;
    constructor (private http: Http) {}

   getApiURL(){
       this.http.get("app/config/development.json").map(res:Response=>res.json())
      .subscribe(data=>{
         this.apiURL = data;

       })

        console.log(this.apiURL);//this returns undefined
   }

}

我要讓this.apiURL遏制的響應http.get 當我創建另一個方法時, this.apiURL的值仍然與方法getAPIURL()

someMethod()
{
   console.log(this.apiURL)//this must contain the response from http.get
}

你可以做這樣的事情。 在您的服務文件中。

//whatever model u defined
       getApiURL():Observable<Object[]>{     
      return this.http.get(this.whateverURL)
                .map(res:Response=>res.json())
                .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
  }

在您的組件文件中

  yourData:Object[];
  //whatever Model u defined.
  //assuming yourService is your service instance which u did in constructor.
  this.yourService.getApiURL()
        .subscribe(
            yourData=>{
              this.yourData=yourData;               
            },err=>{
              console.log(err);
              alert("Something went wrong");
            }
        )
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM