[英]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.