angularjs – 在已解决的承诺中返回一个Observable
发布时间:2020-12-17 17:22:13 所属栏目:安全 来源:网络整理
导读:试图返回一个Observable. 我该怎么办呢? get(url) : Observableany { let headers = new Headers(); this.SetAuthorizationHeader(headers).then(() = { // Resolving a promise return this.http.get(url,{ // -- I need to return the Observable from he
试图返回一个Observable.
我该怎么办呢? get(url) : Observable<any> { let headers = new Headers(); this.SetAuthorizationHeader(headers).then(() => { // Resolving a promise return this.http.get(url,{ // <-- I need to return the Observable from here headers: headers }); }); } 消费(不工作): public GetInfo() : Observable<any> { return this.authHttpClient.get(this.constants.api_base + "/users/info") .map((res: Response) => res.json()); } 谢谢! 解决方法
您只需要返回this.SetAuthorizationHeader(headers)方法,因此在解析SetAuthorizationHeader方法时,它将返回http.get调用observable.
码 get(url) : any { let headers = new Headers(); //return promise here to continue chain & return inner observable. return this.SetAuthorizationHeader(headers).then(() => { // Resolving a promise return this.http.get(url,{ // <-- I need to return the Observable from here headers: headers }); }).map(data => data.json()); } 消费 public GetInfo() : any { //here also it will be any,because you are returning `authHttpClient.get` at the end return this.authHttpClient.get(this.constants.api_base + "/users/info")); } 获取信息消费 this.user.GetInfo().then(obs => obs.subscribe( user => { alert(JSON.stringify(user)); },(error) => { alert(JSON.stringify(error)); } ); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |