将 Observable 引用分配给 map 运算符中的 null 不会产生任何影响

Assigning Observable reference to null inside map operator does not make any effect

我正在尝试创建一个带有 hateoas 实现的通用 DataService。 有一个 REST api /root 提供了所有的 hateoas link。 例如,

{
    _links : {
        login : {
            href : '/login',
            method : 'POST'
        },
        orders : {
            href : '/orders',
            method : 'GET'
        },
        orderById : {
            href : '/order/{id}',
            method : 'GET'

        }
        .......
    }
}

在应用程序加载时,DataService 应该调用 /root api 并将响应存储在实例变量中,比如 rootLinks。它应该在整个会话期间可用。

然后 DataService 应该提供一个 followLinkByName 方法,该方法从可用的 rootLinks 中获取 href 并触发一个新的 http 请求。

const rootUrl: string = '/root';
const baseUrl: string = 'http://localhost:8080';

@Injectable()
export class DataService {

  private observable$: Observable<any>;
  private rootLinks: any;

  constructor(private http: Http) {
    this.ngOnInit();
  }

  ngOnInit() {
    this.getRootLinks().subscribe();
  }

  private getRootLinks() {
    if (this.rootLinks) {
      return Observable.of(this.rootLinks);
    } else if (this.observable$) {
      return this.observable$;
    } else {
      this.observable$ = this.http.get(rootUrl).map(this.extractRootLinkData);
      return this.observable$;
    }
  }

  private extractRootLinkData(response: Response) {
    this.observable$ = null;                             // LINE 1
    let data = response.json();
    this.rootLinks = data._links;
  }


  private extractData(response: Response) {
    let body = response.json();
    return body;
  }



  followLinkByName(linkName: String): Observable<any> {
    let link;
    if (this.observable$) {                              // LINE 2
      return this.observable$.map((res) => {
        link = res._links[linkName];
        // make a http request and return the response
      });
    } else {
      link = this.rootLinks[options.linkName];
      options.link = link;
      // make a http request and return the response
    }
  }

}

我在 core module's providers 数组中添加了这个 DataService, 并且 core module 被导入到 app module

现在 pages 模块中有一个 LoginComponent 使用此 DataService 登录。虽然在第 1 行中,observable$ 被分配给 null,但当从 LoginComponent.

进行调用时,它在第 2 行可用

快照, 1. 在应用程序加载时调用 /root api 并且一旦数据可用,就将可观察对象分配给 null。

2.when 正在尝试登录,

由于 this.http.get(rootUrl) 调用是异步的,您确定在使用 .map(this.extractRootLinkData) 时不会丢失 this 上下文吗?

我认为当调用 extractRootLinkData() 方法作为 map() 的回调时,this 上下文等于 window。所以你在 window 上执行语句 this.observable$ = null 无论如何都不存在。

您可以改用匿名函数:

this.observable$ = this.http.get(rootUrl).map(response => this.extractRootLinkData(response));

... 或绑定 this 上下文:

this.observable$ = this.http.get(rootUrl).map(this.extractRootLinkData.bind(this));

另见:How to access the correct `this` context inside a callback?