如何在外面使用 Angular 6 订阅() 方法的结果?



我正在尝试创建一个只有几个URL的config.json文件,并在服务中读取数据。

.../.../assets/config.json

{
"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 });
}
}

在特定login.service.tsregistration.service.ts中,我调用getConfig()来处理特定的 url。问题是在此服务中返回值未定义,但我需要订阅/getConfig 方法的结果。

现在我正在等待大约 3 个小时的解决方案,但随着我阅读,我确实变得更加困惑,所以我想寻求帮助。

我看到了.map()方法的解决方案(但我想这种方法不再存在(,"承诺",export interface但没有任何效果。

示例 ../registration.service.ts

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);
}
}

最新更新