我仍然在角度2中学习可观察,并且无法弄清楚如何将角度1中的代码转换为角度2。
function promiseFunc() {
var deferred = $q.defer();
$http.post(url, something)
.then(function (response) {
if (response === 1) deferred.resolve(response.data);
else deferred.reject();
}).catch(function (e) {
deferred.reject(e);
});
return deferred.promise;
}
有谁能告诉我如何使用angular 2 observable转换此代码?
编辑:
如果http.post是可选的怎么办?
function promiseFunc(param1) {
var deferred = $q.defer();
if (param1 === 1) {
deferred.resolve(1);
} else {
$http.post(url, something)
.then(function (response) {
if (response.x === 1) deferred.resolve(response);
else deferred.reject();
}).catch(function (e) {
deferred.reject(e);
});
}
return deferred.promise;
}
我在observable中缺少的是调用解析和拒绝的能力。可以在可观察的情况下完成吗?
答案 0 :(得分:3)
someMethod() {
if(param === 1) {
return Observable.of(1);
} else {
return this.http.post(url, something)
.map(
response => {
let data = response.json();
if(data === 1) {
return 1;
}
throw 'some error';
}
);
}
}
然后像
一样使用它this.someMethod().subscribe(
data => console.log(data),
error => console.log(error),
() => console.log('completed')
);