AngularJS 2可观察到的http变化检测
问题描述:
没有做Angular2很长时间,所以,如果我不能正确理解observables ......在组件中我正在订阅位于服务类中的getData。我想要的是让http调用,并在url更改时(也可能是其他任何URL参数)自动发送更改给调用者/订阅者。这怎么能实现?我是否可以正确理解observables?AngularJS 2可观察到的http变化检测
@Injectable()
export class HttpService {
url: string;
constructor(
private http: Http
) {}
getData() {
return this.http.get(`${this.url}`)
.map((res:Response) => res.json());
}
setUrl(url) {
this.url = url;
}
}
答
您的实现,getData()
用途在当时的getData()的任何值this.url
持有调用。换句话说,如果您在更改this.url
后称为getData()
,则不会发生任何事情。
做你的描述,你需要包装内可观察到的不同的URL的流:
import {Subject} from 'rxjs/Subject';
@Injectable()
export class HttpService {
// The `url` property is replaced with an observable emitting a stream of URLs.
private _urlsStream: Subject<string> = new Subject<string>();
constructor(private http: Http) {}
// The http.get() now gets its urls from the url stream.
// Every time a new url is pushed to the stream, a new request is executed.
getData() {
return this._urlsStream.asObservable()
.mergeMap((url: string) => this.http.get(url))
.map((res: Response) => res.json());
}
setUrl(url) {
// Setting an url pushes the given url to the stream.
this._urlsStream.next(url);
}
}
这段代码肯定是比原来的版本更加复杂。我已经添加了意见,以澄清,但如果你是RxJS的新手,我强烈建议你花一些时间reading the manual和watching some tutorials。
你想了解:
- 不同类型的观测值(我用了
Subject
,这是观察到的一种特殊类型,它可以发出两种价值观和进行订阅)。 - 不同类型的操作符(我使用
mergeMap()
将一个observable(URL流)“投影”到另一个observable(HTTP请求)中。