我试图在成功完成Promise之后返回一个observable,但该函数没有返回Observable.要特定于代码,我想从存储中获取auth令牌(返回promise),然后在获取数据之后,然后生成对Api的Post请求(返回Observable).通过这样做,sublime文本在函数上给出了一个错误,"声明类型既不是'void'也不是'any'的函数必须返回一个值"下面是我的代码,
logout() : Observable{ this.userData.getAuthToken().then((token)=>{ this.token = token; this.headers = new Headers ({ "X-USER-TOKEN": token }); this.options = new RequestOptions ({ headers: this.headers }); var logout_url = "Api logout method"; return this.http.post(logout_url,{},this.options) .map (res => res.json()) }); }
如果我只是做一个帖子请求,那么它会像这样返回
return this.http.post(logout_url,{},this.options) .map (res => res.json())
但是当我尝试获取数据时,它不会从此发布请求中返回值.任何帮助都感激不尽!提前致谢
使用fromPromise
的承诺转化为可观察到的,并使用mergeMap
发出HTTP响应为合成观察到:
import { Observable } from 'rxjs/Observable/';
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
logout(): Observable{
return Observable.fromPromise(this.userData.getAuthToken()).mergeMap(token => {
this.token = token;
this.headers = new Headers({
"X-USER-TOKEN": token
});
this.options = new RequestOptions({
headers: this.headers
});
var logout_url = "Api logout method";
return this.http.post(logout_url, {}, this.options).map(res => res.json());
});
}
随着RXJS> 6,fromPromise
被合并到from
函数中并使用mergeMap
,您需要首先使用pipe
。所以这段代码会起作用
import { Observable, from } from "rxjs"; import { map, mergeMap } from "rxjs/operators"; logout(): Observable{ return from(this.userData.getAuthToken()).pipe(mergeMap(token => { this.token = token; this.headers = new Headers({ "X-USER-TOKEN": token }); this.options = new RequestOptions({ headers: this.headers }); var logout_url = "Api logout method"; return this.http.post(logout_url, {}, this.options).map(res => res.json()); })); }