本文介绍了angular2-在可观察完成后导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的UserService中,我有一个像这样可观察到的http:

I have an http observable like so, in my UserService:

logout() {
    return this.http.delete(this.baseUrl + url, {
          headers: this.headers()
        }).map((res: IResponse) => {
          var json = res.json();
          json.headers = res.headers;
          return json;
        }).subscribe((response) => {
          //DO SOMETHING, THEN ----
          return res;
        });
}

我创建了一个可观察对象,并创建了一个订阅(response),这是返回的成功值.

I have created an observable, and created a subscription (response) which is the returned success value.

现在,在我的组件中,我想调用UserService.logout(),然后导航到新路线:

Now, in my component, I want to call UserService.logout() and THEN navigate to a new route:

logout() {
    this.userService.logout();
    this.router.navigate(['LandingPage']);
  }

很明显,这可能是异步发生的,我可能会在退出之前导航.

Obviously, this could happen asynchronously and I may end up navigating before I logout.

使用诺言,我可以做这样的事情:

Using promises, I could do something like this:

this.userService.logout().then(() => { this.router.navigate(['LandingPage']);});

this.userService.logout().then(() => { this.router.navigate(['LandingPage']);});

我如何对可观察对象做同样的事情?在我的UserService类中,我想创建一个可观察的对象,订阅它,在成功或出错时做一些事情,然后从我的视图组件中导航.

How can I do the same thing with observables? In my UserService class I want to create an observable, subscribe to it, do some stuff on success or on error, THEN navigate from my view component.

推荐答案

您实际上可以使logout方法返回一个promise并像往常一样使用它.不必是可观察的:

You can actually make logout method return a promise and use it as normal. It doesn't have to be Observable:

logout() {
    return new Promise((resolve, reject) => {
        this.http.delete(this.baseUrl + url, { headers: this.headers() })
            .map((res: IResponse) => {
              var json = res.json();
              json.headers = res.headers;
              return json;
            })
            .subscribe(data => {
              //DO SOMETHING, THEN ----
              resolve(data);
            }, error => reject(error));
    });
}

logout() {
  this.userService.logout().then(response => this.router.navigate(['LandingPage']))
}

这篇关于angular2-在可观察完成后导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 06:47