我是typescript的新手,想将一个方法返回值传递给另一个方法。因为第二种方法依赖于第一种方法返回值。 以下是我的代码:
// First method call
this.someService.getLoggedinUser()
.subscribe(uid => {
console.log(uid);
this.uid = uid;
});
//Second method call
this.someService.getUser(this.uid.toUpperCase())
.subscribe(user => {
this.user = user;
});
我正在尝试将mehtod 1返回值传递给方法2,例如:
constructor(private someService:SomeService){
this.someService.getUser(uid: string => {
this.someService.getLoggedinUser()
.map(uid => {
return uid.toUpperCase();
});
})
.subscribe(user => {
this.user = user;
}); }
请帮助我实现这一目标。
答案 0 :(得分:2)
angular2中的最佳方法
您可以使用flatMap
然后,这是你如何链接两个电话:
private someMethod{
this.someService.getLoggedinUser()
.subscribe(uid => {
console.log(uid);
this.uid = uid;
})
.flatMap((uid) =>
this.someService.getUser(this.uid.toUpperCase())
.subscribe(user => {
this.user = user;
});
}
答案 1 :(得分:0)
你可以将第一个方法调用返回的值赋给本地var,然后在下一个方法中使用它,或者你可以在第一个可观察方法中这样做。
我在我的回购https://github.com/rahulrsingh09/AngularConcepts
中使用了这个getLukeSkywalkerObservable(){
return this.http.get('http://swapi.co/api/people/1/')
.map(res => {
return res.json(); // using maps to filter data returned form the http call
}).map(data => {
return data; // using maps of maps to filter data returned form the map
}).flatMap((jedi) => this.http.get(jedi.homeworld))
.map(res => {
return res.json().name; // using flat maps to combine data returned from two observables into one
}).catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
答案 2 :(得分:0)
这是一个简单的表格:
var user;
this.someService.getLoggedinUser()
.subscribe(uid => this.someService.getUser(uid.toUpperCase())
.subscribe(user => this.user = user));
答案 3 :(得分:0)
您可以在元素请求的Observable中调用第二个方法。
public test() {
this.someService
.getLoggedinUser()
.subscribe(uid => {
const uppercaseUid = uid.toUpperCase();
this.someService
.getUser(uppercaseUid)
.subscribe(user => this.user = user);
});
}
答案 4 :(得分:0)
您可以使用嵌套订阅调用来实现此目的。
// assigning self = this for debugging purpose when typing variable in console
// example typing self.uid gives value inside subscribe but this.uid is
//undefined.
let self = this;
self.someService.getLoggedinUser()
.subscribe(uid => {
console.log(uid);
self.uid = uid;
//Second method call
self.someService.getUser(uid.toUpperCase())
.subscribe(user => {
self.user = user;
});
});