Javascript 如何在外部使用Angular 6 subscribe()方法的结果?
我试图创建一个只包含几个URL的config.json文件,并读取服务中的数据 …/…/assets/config.jsonJavascript 如何在外部使用Angular 6 subscribe()方法的结果?,javascript,angular,http,get,Javascript,Angular,Http,Get,我试图创建一个只包含几个URL的config.json文件,并读取服务中的数据 …/…/assets/config.json { "registration" : "localhost:4200/registration" "login" : "localhost:4200/login" } ../services/config.service.ts export class ConfigService { result; configUrl = '../../asse
{
"registration" : "localhost:4200/registration"
"login" : "localhost:4200/login"
}
../services/config.service.ts
export class ConfigService {
result;
configUrl = '../../assets/config.json';
constructor(private http: HttpClient) {}
getConfig() {
return this.http.get(this.configUrl).subscribe((data) => { this.result = data });
}
}
export class RegistrationService {
private api_url;
constructor(private http: HttpClientModule, private cs: ConfigService) {
this.api_url = this.cs.getConfig();
}
}
在特定的login.service.ts
和registration.service.ts
中,我调用getConfig()
来处理特定的URL。问题是,在这个服务中,返回值未定义,但我需要subscribe/getConfig方法的结果
现在我看了大约3个小时的解决方案,但随着我读得越来越多,我确实变得越来越困惑,所以我想寻求帮助
我看到了.map()
方法的解决方案(但我想这个方法已经不存在了),有“承诺”,有导出接口
,但没有任何效果
../registration.service.ts示例
export class ConfigService {
result;
configUrl = '../../assets/config.json';
constructor(private http: HttpClient) {}
getConfig() {
return this.http.get(this.configUrl).subscribe((data) => { this.result = data });
}
}
export class RegistrationService {
private api_url;
constructor(private http: HttpClientModule, private cs: ConfigService) {
this.api_url = this.cs.getConfig();
}
}
您的配置服务:
getConfig() {
return this.http.get(this.configUrl).toPromise();
}
您的注册服务:
async exampleMethod() {
try {
this.api_url = await this.cs.getConfig();
console.log(this.api_url);
} catch(e) {
throw Error(e);
}
}
是的,成功了,谢谢。我有点困惑,因为另一个方法中的console.log(this.api_url)也未定义,但我想这是因为异步工作流。但是对于api,它可以工作并获得所需的URL。非常感谢。Np,我建议您使用.toPromise()并使用async wait。这是“smoothie”,没有必要“订阅”http请求。例如,订阅web套接字更有意义。