如何在可观察内部订阅并返回可观察



我想获取可观察量的结果并进行一些更改,然后再次返回可观察量类型的结果,以便组件订阅。 这是我的代码:

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import 'rxjs/add/observable/of';
import {Observable} from 'rxjs/Observable';

get_items() {
this.http.get(this.router_url).map(res => res.json()).catch(this.handleRequestError).subscribe(
(result) => {
result = result.data[0].my_item
return Observable.of( data: [{my_items: result}]});
},
(error) => {}
)
}

问题出在使用并尝试 get_items(( 的 .subscribe 结果的组件中,他们得到的错误为:未捕获(承诺(: 类型错误:

this.generalService.get_items(...订阅不是一个函数

但是当我回来时,只是:

return Observable.of( data: [{my_items: result}]});

它工作正常,但这不是我想要的 无论如何,结果类型是可观察的,为什么我会收到此错误? 提前致谢

你可以做这样的事情:

get_items() {
this.http.get(this.router_url).map(res => {
const result = res.json();
return {data: [{my_items: result.data[0].my_item}]};
});
}

map运算符是您在实际订阅响应之前应修改响应的位置。

正如角度文档所说,HttpClientget()返回一个可观察的。因此,您不必创建一个新的。

/**
* Construct a GET request which interprets the body as JSON and returns it.
*
* @return an `Observable` of the body as type `T`.
*/
get<T>(url: string, options?: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe?: 'body';
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
}): Observable<T>;

试试这个。并将any替换为表示响应的接口;

import { Observable } from "rxjs";
get_items() Observable<any>{
return this.http.get<any>(this.router_url).map(res => res.json());
}

并在组件中。

this.service.get_items().subscribe((res) => {
// request data will be here in the res
});

我遇到了类似的事情,这就是我解决它的方式。

FooService.ts

private fetchFoo(): Observable<any> {
return this.httpService.get('/foo');
}
public async getFoo(): Promise<Foo[]> {
if(this.foo.length === 0) {
return this.fetchFoo()
.toPromise() <-- use in place of .subscribe
.then((response) => {
this.foo = response.data;
return this.foo;
}, (err) => {
console.debug(err);
return this.foo;
});
} else {
return this.foo;
}
}

AnyComponent.ts

public getFoo(): void {
this.fooService.getFoo().then((response) => {
this.doSomething(response);
})
}

使用.toPromise而不是.subscribe来处理可观察量仍将执行网络调用,并将公开的服务函数设置为随后可订阅的承诺,而不是需要取消订阅的订阅。

最新更新