仅在升级到角度 15 后,路由器 getCurrentNavigation 始终返回 null

ibr*_*mgb 7 router typescript angular-ui-router angular

这个问题仅在升级到 Angular 15 后出现,我将一个状态属性传递给路由器,但 this.router.getCurrentNavigation() 返回一个空值,该值已router.navigate在另一个组件中传递

A组份:

在此输入图像描述

组分B:

在此输入图像描述

我可以使用组件 B 访问状态,this.state = history.state;this.state = this.router.getCurrentNavigation()?.extras?.state ?? {};不起作用,它说 getCurrentNavigation() 返回 null。那是什么?

小智 6

当我们升级到 Angular 15 时,我们遇到了同样的问题。我们通过添加新的解析器解决了这个问题。该解析器可以使用 getCurrentNavigation() 访问当前路线,因此可以将“额外”数据返回给组件。

@Injectable()
export class MyComponentResolver implements Resolve<MyComponentExtraData> {
  constructor(private router: Router) {
  }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): MyComponentExtraData{
  
    return this.router.getCurrentNavigation().extras?.state['MyData'];
  }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用activatedRoute.snapshot字典访问组件构造函数中解析器返回的数据,没有任何问题。

constructor(private activatedRoute: ActivatedRoute) {
 
    let myData = this.activatedRoute.snapshot.data['myData'] /* the myData key depends on how you defined the resolver in your route declaration*/
  }
Run Code Online (Sandbox Code Playgroud)


Mat*_*ler 5

从 Angular 15 开始,this.router.getCurrentNavigation()可能会返回 null,因为组件是在导航后实例化的。

另一种方法是从 Location 访问状态(来自 的位置@angular/common

  import { Location } from '@angular/common';

  constructor(private location: Location) {
    location.getState() // do what you want 
  }
Run Code Online (Sandbox Code Playgroud)