我按照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)
时,说在登录功能内部,它可以正常工作。那是为什么?
答案 0 :(得分:4)
您需要确保传递给map()的回调函数绑定到此:
.map(response => this.extractData(response))