无法使用angular 2 Subject读取undefined属性'next'

时间:2016-12-08 21:08:26

标签: 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);
    }
}

extractData内部,我打电话给

this.authenticatedSource.next(true);

但它会引发错误:

Cannot read property 'next' of undefined

当我在extractData之外调用this.authenticatedSource.next(true)时,说在登录功能内部,它可以正常工作。那是为什么?

1 个答案:

答案 0 :(得分:4)

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

.map(response => this.extractData(response))