在我的Angular 4应用程序中,我有一个必须返回一个observable的方法,
这个方法有3个条件,第一个和第二个条件进行get调用,但是第三个条件不能做任何事情,在这种情况下我也必须返回一个observable,因为这个方法是.flatmap运算符的第一部分,所以要链接flatmap的第二部分我需要从第一部分开始观察.
这个方法有3个条件,第一个和第二个条件进行get调用,但是第三个条件不能做任何事情,在这种情况下我也必须返回一个observable,因为这个方法是.flatmap运算符的第一部分,所以要链接flatmap的第二部分我需要从第一部分开始观察.
我尝试:返回新的Observable< void>();但我有这个错误:
ERROR TypeError: Cannot read property ‘subscribe’ of undefined
- loadModelData() {
- this.customerService.getModelDetail(this.code)
- .subscribe(response => {
- this.selected = response.body as Customer;
- });
- }
- }
- getModelDetail(code) {
- const params = new HttpParams().set('projection','withBalance');
- return this.endPointUrlService.loadMaps(this.entityLink)
- .flatMap((res) => {
- return this.http.get(this.endPointUrlService.cutLinks(
- this.endPointUrlService.map.get('customers')) + '/' + code,{observe: 'response',params: params})
- .map((response) => <any>response);
- })
- }
这是来自名为endPointUrlService的支持服务的方法,checkIfMapIsReady()是必须在第三种情况下返回void observable的方法
- loadMaps(entityLink: EntityLink[]): Observable<void> {
- console.log(entityLink);
- for (const i in entityLink) {
- if (entityLink.hasOwnProperty(i)) {
- return this.checkIfMapIsReady(entityLink[i].name,entityLink[i].searchMap,entityLink[i].endPoints[0])
- }
- }
- }
- public checkIfMapIsReady(modelName: string,mapName: string,endPoints: string) {
- if (this.map.get(modelName) === undefined) {
- console.log('endpoint url service All maps undefined ' + modelName);
- return this.getLinks(modelName,this.mapNames.get(mapName),false)
- } else {
- console.log('endpoint url service Populate only ' + mapName);
- if (this.mapNames.get(mapName).get(endPoints) === undefined) {
- return this.getLinks(modelName,true)
- } else {
- return new Observable<void>();
- }
- }
- }
也许Observable.empty()是一个更好的选项,因为它不会发出任何值,下游运算符不会有它返回的问题!
注意,下游flatMap(res => …)和subscribe()不会触发.
既然你没有使用res,我认为这是理想的效果?
为了更好地衡量,请返回类型Observable< any>.
我认为下面在逻辑上等同于发布的checkIfMapIsReady(),
- public checkIfMapIsReady(modelName: string,endPoints: string) {
- const map = this.map.get(modelName);
- const name = this.mapNames.get(mapName);
- const endPointCheck = name ? name.get(endPoints) : null;
- const links = !endPointCheck
- ? this.getLinks(modelName,name,!!map) // !! gives boolean true or false
- : Observable.empty();
- const msg = !map
- ? 'endpoint url service All maps undefined ' + modelName
- : 'endpoint url service Populate only ' + mapName
- console.log(msg);
- return links;
- );