这是HTTP服务,发出获取请求,提取 longArray.js ;
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/Rx';
@Injectable()
export class HttpService {
constructor(
private http: Http
) {}
getHttpReq(url: string): Promise<any> {
return new Promise((resolve, reject) => {
this.http.get('http://192.168.0.189/longArray.js')
.map(response => response.json())
.subscribe(
function(response) {
console.log("Success Response ");
resolve(response);
},
function(error) {
console.log("Error happened " + error);
reject(error);
},
function() {
console.log("Subscription is completed ");
}
);
});
}
}
这是一种返回bool承诺的方法,具体取决于 getHttpReq (在 HttpService 中)是否 longArray.js ;
getLongArrayTryOrFail(): Promise<boolean> {
return new Promise((resolve,reject) => {
this.httpService.getHttpReq('')
.then(response => resolve(true))
.catch(error => reject(false))
});
}
答案 0 :(得分:1)
- 这种创建HTTP服务的方法是否正确?
醇>
不,通常你不应该考虑将Promise与Observable一起使用。
- 基本上是getHttpReq(在类HttpService中)订阅了 可观察的&amp;根据要么解决或拒绝承诺 订阅成功的响应或错误。我是对的吗?
醇>
您的Promise实施没有任何问题,但我不明白为什么您不再使用Observable
。它拥有你正在寻找的一切+他们是懒惰的。下面是几行代码中的Observable实现。
<强>代码强>
export class HttpService {
constructor(
private http: Http
) {}
getHttpReq(url: string): Observable<any> {
return this.http.get('http://192.168.0.189/longArray.js')
.map(response => response.json());
});
}
}
//consumption
getLongArrayTryOrFail(): Observable<boolean> {
return this.httpService.getHttpReq('')
.map(response => true)
.catch(error => Observable.throw(false));
});
}