簡體   English   中英

在 Angular2 中的 router.navigate 之后執行代碼

[英]Executing code after router.navigate in Angular2

我想知道在使用角度路由器導航到不同的“視圖”后是否有辦法執行某些操作。

this.router.navigate(["/search", "1", ""]);
// Everything after navigate does not not get executed.
this.sideFiltersService.discoverFilter(category);

this.router.navigate 返回一個 promise,所以你可以簡單地使用:

 this.router.navigate(["/search", "1", ""]).then(()=>{ // do whatever you need after navigation succeeds });

不完全確定上下文,但一個選項是使用ActivatedRoute訂閱 URL 中的更改

https://angular.io/docs/ts/latest/guide/router.html#!#activated-route

下面是一個例子:

...
import { ActivatedRoute } from '@angular/router';
...

private _routerSubscription: any;

// Some class or service

constructor(private _route: ActivatedRoute){
    this._routerSubscription = this._route.url.subscribe(url => {
        // Your action/function will go here
    });
}

如果 url 不是您所需要的,那么您可以在ActivatedRoute中訂閱許多其他可觀察對象,這些可觀察對象列在該鏈接中。

訂閱可以在constructor()ngOnInit()具體取決於最適合您的方式,請記住在自己之后清理並在ngOnDestroy()取消訂閱 :)

this._routerSubscription.unsubscribe();
// In javascript
this.router.navigate(["/search", "1", ""])
    .then(succeeded => {
        if(succeeded)
        {
            // Do your stuff
        }
        else
        {
            // Do some other stuff
        }
    })
    .catch(error => {
        // Handle the error
    });

// In typescript you can use the javascript example as well.
// But you can also do:
try
{
    let succeeded = await this.router.navigate(["/search", "1", ""]);
    if(succeeded)
    {
        // Do your stuff
    }
    else
    {
        // Do some other stuff
    }
}
catch(error)
{
    // Handle the error
}

如果您是從導航ComponentAComponentB導航,你可以做任何行動之后再ngOnInit()的函數ComponentB ,取決於在路由傳遞的參數。

您還必須確保沒有正在進行的訂閱......我遇到了同樣的問題,就我而言,有一個訂閱改變了路線。 所以路線改了兩次。 但實際上你可以使用 promises,沒錯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM