我有一个组件的方法,但是它有一些意外的行为:
private fetchExternalStyleSheet(outerHTML: string): string[] {
let externalStyleSheetText: string;
let match: RegExpExecArray;
const matchedHrefs = [];
while (match = this.hrefReg.exec(outerHTML)) {
matchedHrefs.push(match[1]);
}
const requestedUrl = this.url + matchedHrefs[0];
this._ApiService.makeRequest(requestedUrl, ActionType.content)
.subscribe((response: any) => {
externalStyleSheetText = response.content;
console.log('inside subscribe', externalStyleSheetText); // => expected content
});
console.log('outside subscribe', externalStyleSheetText); // => undefined
return this.parseStyleSheetText(externalStyleSheetText);
}
在内部.subscribe
方法externalStyleSheetText
中的绑定具有期望值,而在外部它给我未定义。我想这与订阅方法的异步行为有关。我复习了一些相关问题,但仍未解决,因为每个人都建议通过subscribe
生命周期挂钩中的ngOnInit
发出请求,这意味着我们在组件初始化之前就得到了请求结果。但就我而言,我必须在ngOnInit
之外制作它,所以我得到了undefined
答案 0 :(得分:1)
要解决此问题,我想您必须使fetchExternalStyleSheet
返回一个可观察的对象,并从外部调用中进行订阅。因此fetchExternalStyleSheet
看起来像这样:
private fetchExternalStyleSheet(outerHTML: string): Observable<string[]> {
let externalStyleSheetText: string;
let match: RegExpExecArray;
const matchedHrefs = [];
while (match = this.hrefReg.exec(outerHTML)) {
matchedHrefs.push(match[1]);
}
const requestedUrl = this.url + matchedHrefs[0];
return this._ApiService.makeRequest(requestedUrl, ActionType.content)
.pipe(map((response: any) => {
externalStyleSheetText = response.content;
return this.parseStyleSheetText(externalStyleSheetText);
}));
}
,并在通话中订阅结果,如下所示:
callerMethod() {
this.fetchExternalStyleSheet('<h1>Test</h1>').subscribe(response => {
this.parsedStylesheet = response;
})
}
我进行了一次堆叠突击,单击按钮会调用callerMethod
:https://stackblitz.com/edit/angular-tpogff