我知道这个问题已经被问过很多次了,但仍然没有一个答案能解决我的问题。我有一个从 json 文件中获取 URL 的服务。
@Injectable()
export class HostConfigService {
getHostUrl()
{
return this.http.get("File path").map((response : Response) =>
response.json()); // this returns a URL ex: http://localhost:8080
}
}
我想使用上面 URL 的响应在多个文件中构造 URL,以便从 Angular 应用程序进行其余调用。
export class GetData{
constructor(private hostConfigService: HostConfigService, private _http:
Http) { }
getData(){
this.hostConfigService.getHostUrl().subscribe((res) => this.hostUrl =
res.hostUrl); //this.hostUrl should return undefined outside subscribe
block
this.restUrl = this.hostUrl + "/getData";
return this._http.get(this.restUrl).map((response :
Response) => response.json());
}
}
来自 getData 函数的响应也从订阅中读取。我已经在 subscribe 中使用了 subscribe ,但这给了我错误 Property 'subscribe' does not exit on type 'void'。您能帮我解决这个问题吗?
最佳答案
你应该使用环境,但如果你不想,使用函数的正确方法是这样的
export class GetData {
constructor(private hostConfigService: HostConfigService, private _http: Http) { }
getData() {
this.hostConfigService.getHostUrl()
.flatMap(url => this._http.get(url).map((response : Response) => response.json()));
}
}
发生的情况是,您进行第一个调用,一旦结果出现,您就进行第二个调用。
关于angular - 来自订阅的异步 get 请求的响应将在另一个 get 请求中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47198035/