angular - 在 Angular 中获取订阅之外的结果
问题描述
我有一个组件的方法,但它有一些意想不到的行为:
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
解决方案
为了解决这个问题,我想你必须让fetchExternalStyleSheet
return 成为一个 observable,并从外部调用订阅它。所以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;
})
}
我做了一个stackblitz,点击一个按钮调用callerMethod
:https ://stackblitz.com/edit/angular-tpogff
推荐阅读
- c# - 从子类中的父类访问设置的最佳方式
- c++ - 如何在 SDL2 中嵌套视口
- filter - 如何使用 COUNT 公式找到唯一条目?
- javascript - 如果我的组件作为 ReactJS 中的儿童道具传递给布局组件,如何访问布局组件中的道具?
- python - Python对象初始化问题
- semantic-ui - 语义中的段转换不起作用
- uwp - 从命令行运行 UWP 应用程序是“仅”显示应用程序的启动屏幕
- c# - 当 Listview Item Value = x 时应用必填字段验证器
- regex - 如何使用正则表达式拆分以数字开头并以单词结尾的单词,反之亦然
- sip - SIP 客户端在 CANCEL 上响应 481