来自订阅异步获取请求的响应将在另一个获取请求中使用

Response from Subscribe of async get request to be used in another get request

我知道这个问题已被问过很多次,但 none 的答案仍然解决了我的问题。我有一项服务可以从 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,但这给了我错误 属性 'subscribe' does not exist 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()));
  }
}

发生的情况是您进行第一次调用,一旦结果出现,您进行第二次调用。

由于您已经从静态文件中获取主机 url,因此使用 environments

会更好

environments/environment.ts 文件中,您可以这样定义 url:

export const environment = {
    ...
    hostUrl: 'www.thisismyhosturl.com',
    ...
};

接下来你可以在你的服务中使用这个变量

import { environment } from '../../../environments/environment';

export class GetData{
constructor(private _http: Http) { }

    getData(){
        this.restUrl = environment.hostUrl + "/getData";
        return this._http.get(this.restUrl).map((response : 
        Response) => response.json());
    }
}

使用这种方法就不需要 hostConfigService

感谢@trichetriche,使用平面图解决了我的问题。伙计们,我不能使用 environment.ts 来存储主机 URL,因为每个用户的主机 URL 都是不同的,因此我需要将它们存储到资产文件夹中的静态文件中