首页 > 解决方案 > Angular路由器在检索状态对象时如何将window.history.state转换为一个类

问题描述

我正在使用以下代码示例将对象传递给使用状态的路由

@Component({
  template: `<a (click)="navigateWithState()">Go</a>`,
})
export class AppComponent  {
  constructor(public router: Router) {}
  navigateWithState() {
    this.router.navigateByUrl('/123', { state: { hello: 'world' } });
  }
}

在阅读状态时,我想将其转换为类对象。如何将其转换为类对象?

@Component({
  selector: 'app-details-page',
  template: '<pre>{{ state$ | async | json }}</pre>'
})
export class DetailsPageComponent implements OnInit {
  state$: Observable<MyClass>;

  constructor(public activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    this.state$ = this.activatedRoute.paramMap
      .pipe(map(() => (window.history.state) as MyClass))
  }
}

谢谢

标签: angular

解决方案


推荐阅读