【发布时间】:2016-04-11 08:34:46
【问题描述】:
我使用angular2/http 对远程服务器进行了http 调用,这一切都非常好用。但是我在使用它返回的 observables 时遇到了麻烦。
当我进行 http 调用时,我会经历 3 个不同的组件。
(为了方便起见,我只调用 3 种不同的方法,因为它的工作原理相同)
我想知道它是否可以做,是在同一个 observable 上使用两次订阅,或者是否有一种方法可以调用一些函数,这样我就可以在请求中添加日志记录,而不是每次都添加它我进行 http 调用的位置。
request(type: RequestMethod, url: string, data: any) {
let params: URLSearchParams = new URLSearchParams();
let req: RequestOptions;
let headers = new Headers();
for (let key in data) {
params.set(key, data[key]);
}
if (type === 0) {
req = new RequestOptions({
method: type,
search: params
});
} else {
headers.append('Content-Type', 'application/x-www-form-urlencoded');
req = new RequestOptions({
method: type,
body: params.toString(),
headers: headers
});
}
console.log('Http Request: ' + url);
console.log(req);
return this.http.request(this.testUrl + url, req)
.map((res: Response) => res.json());
// .subscribe(
// data => {
// console.log('Data Return for ' + url);
// console.log(data.data);
// // return data; //i removed this subscribe so i can
// }, //pass the map back through and
// err => { //use the subscribe later in the initial call
// this.logError(url, err);
// },
// () => {
// if (afterSuccess) {
// afterSuccess();
// }
// console.log('Completed '+ url);
// }
// );
}
logError(url: string, err: any) {
console.log('Error in call: ' + url);
console.log(err);
}
get(url: string, data: any) {
return this.request(RequestMethod.Get, url, data);
}
post(url: string, data: any) {
return this.request(RequestMethod.Post, url, data);
}
emailExists(email_address: string, user_type?: string) {
let data: any = {};
data.email_address = email_address;
data.service_provider_id = this.service_provider_id;
if (user_type) {
data.user_type = user_type;
}
return this.get('emails/email-address/exists', data);
}
ngOnInit() {
this.emailExists('an.email@gmail.com').subscribe(data => {
this.email = data.data;
console.log('in Signin');
console.log(this.email);
}, err => {
console.log(err);
}, () => {
});
}
在request 方法中,我希望能够调用console.log 来打印出使用的url 并打印从服务器接收到的数据或任何错误。
我知道我可以在ngOnInit() 的emailExists() 调用中将其添加到订阅的成功和错误部分,但这意味着我需要将它们放在整个应用程序的每个调用中。
提前感谢您的帮助和时间。
【问题讨论】: