我遇到Angular 2 / web服务调用问题。我的想法是将服务创建为可注入的,以便在必须进行本地化的组件中使用它(在这些术语中,使用不同的语言)。我的字符串存储在数据库中,我需要做的是使用Web服务将它们存储在关联数组中。然后提供通过键获取值的方法。这是我的示例代码:
import {Injectable} from "@angular/core";
import { Http, Headers, RequestOptions, Response } from "@angular/http";
import "rxjs/add/operator/map";
import "rxjs/add/operator/share";
import myGlobals = require("./global");
@Injectable()
export class LocalizationService {
private serviceUrl = myGlobals.urlPrefix + "api/public/Localization.asmx/GetStrings"; // url to web api
private observable: any;
private locString: {};
private finished: boolean = false;
constructor(private http: Http) {
this.loadStrings("EN");
}
private loadStrings(LanguageCode: string): void {
let body: string = JSON.stringify({ LanguageCode });
let headers: Headers = new Headers({
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json"
});
let options: RequestOptions = new RequestOptions({ headers: headers });
this.observable = this.http.post(this.serviceUrl, body, options)
.map(response => {
this.observable = null;
let responseText: string = response.text().substring(0, response.text().lastIndexOf("{"));
this.locString = JSON.parse(responseText).Data;
this.finished = true;
})
.share();
return;
}
public getStr(code: string): string {
let returnString: string;
try {
returnString = this.locString[code];
}
catch (error)
{
returnString = "";
}
return returnString;
}
}
现在我无法解决:构造函数调用Web服务并立即结束,它不会等待响应。因此,当我在我的组件中使用此可注入服务时,必须以正确的语言呈现,在渲染时不会加载字符串。确切地说,当我将断点设置为.map()时,它永远不会被击中。这不是最糟糕的问题,我可以使用promise做到这一点,因为我在app中的其他地方做这件事。当我需要调用Web服务时,Promise对我有用。问题是它不等待从服务器重放。我已经检查了其他问题和答案,例如
What is the correct way to share the result of an Angular 2 Http network call in RxJs 5?
但这对我没有任何帮助。我不能让应用程序等到响应返回。有谁能告诉我我做错了什么?