无法使用 angular 2 主题读取未定义的属性“next”

Upv*_*ote 0 angular

我实现了这里所描述的双向服务通信https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Subject }    from 'rxjs/Subject';

@Injectable()
export class UserService {

    private authenticatedSource = new Subject<boolean>();
    authenticated$ = this.authenticatedSource.asObservable();

    //..

    login(): void {

        // ...

        return this.http.post(this.apiUrl + '/signup', user, options)
          .map(this.extractData)
          .catch(this.handleError);
    }
}
Run Code Online (Sandbox Code Playgroud)

extractData我调用的内部函数

this.authenticatedSource.next(true);
Run Code Online (Sandbox Code Playgroud)

但它抛出一个错误:

Cannot read property 'next' of undefined
Run Code Online (Sandbox Code Playgroud)

当我this.authenticatedSource.next(true)在 extractData 外部调用时,比如在登录函数内部,它工作正常。这是为什么?

JB *_*zet 6

您需要确保传递给 map() 的回调函数绑定到此:

.map(response => this.extractData(response))
Run Code Online (Sandbox Code Playgroud)