首页 > 解决方案 > 在 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绑定具有预期值,而外部它给了我未定义的值。我想它与订阅方法的异步行为有关。我回顾了一些相关的问题,但仍然没有解决,因为每个人都建议通过生命周期钩子发出请求subscribengOnInit这意味着我们在组件初始化之前得到请求结果。但就我而言,我必须在外面做ngOnInit,所以我得到undefined

标签: angulartypescriptobservable

解决方案


为了解决这个问题,我想你必须让fetchExternalStyleSheetreturn 成为一个 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,点击一个按钮调用callerMethodhttps ://stackblitz.com/edit/angular-tpogff


推荐阅读