我正在尝试为我的Ionic2-Angular2应用程序扩展HTTP类。主要问题来自从(本地|会话)存储中获取一个物品,该存储在ionics2中返回了诺言,我必须将其转换为可观察的(或至少我认为是因为那是因为),以使扩展程序与一致我要扩展的类的每个函数的返回值类型。
getCustomRequest(url:string, method:string, options?: RequestOptionsArgs, body?:any):Observable<any>{
let headers = new Headers({'Content-Type': 'application/json'});
return Observable.fromPromise(
this.storage.get("authToken").then(
data => {
console.log('Token '+data);
headers.append("Authorization", 'Token '+data);
return this.getNewReq({method, headers, body, url}, options);
},
error => {
console.log('no token!');
return this.getNewReq({method, headers, body, url}, options);
}
)
);
}
private getNewReq(reqOptObject, options):Request{
let reqOpt = new RequestOptions(reqOptObject);
if (options) {
reqOpt = reqOpt.merge(options);
}
return new Request(reqOpt);
}
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
return super.request(url, options);
}
post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>{
return this.getCustomRequest(url, 'POST', options, body)
.map( newReq => { console.log(newReq); return this.request(newReq); });
}
错误消息是[line return this.getCustomRequest(url ...]:键入'observable>'不能分配给'observable'。 "可观察到"不能分配"响应"。类型中缺少属性"类型" "可观察"。
因为 this.request()
返回 Observable
,我认为您需要使用merge
而不是map
post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>{
return this.getCustomRequest(url, 'POST', options, body)
.merge( newReq => { console.log(newReq); return this.request(newReq); });
}