gpt4 book ai didi

angular - activatedRoute 快照在 TS 类构造函数中不起作用

转载 作者:行者123 更新时间:2023-12-02 17:20:44 25 4
gpt4 key购买 nike

我在 typeScript 和 angular 2 中遇到了问题。我的 TS 类如下所示,

'import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from '@angular/router';

@Component({
selector: 'app-blogdetail',
templateUrl: './blogdetail.component.html',
styleUrls: ['./blogdetail.component.css']
})
export class BlogdetailComponent implements OnInit {

blogId:any;
title:any;

constructor(private _activatedRoute:ActivatedRoute) {
//Does not work
// this.blogId = this._activatedRoute.snapshot.params['id'];
//this.title= `This is blog detail for blogID:${this.blogId}`;

}

ngOnInit() {
this.blogId = this._activatedRoute.snapshot.params['id'];
this.title= `This is blog detail for blogID:${this.blogId}`;
}

}'

我必须在 ngOnit 事件中获取路由参数。当我最初在 TS 类构造函数中使用相同的代码(获取参数)时,我得到的 blogId 变量值为 undefined 。据我了解事件的顺序,它们类似于下图,![流量] /image/41fpe.png

我们是否必须始终在 ngOnIt 中获取 activatedRoute 快照值??

最佳答案

你是对的。发生的事情是,当您的组件为您的 View 启动时,您的 constructor 被调用。但是由于那时只是创建了新实例,所以路由没有被激活,因此您没有获得路由参数。另一方面,当您在 OnInit 中使用它时,路由被激活并且您获得参数。不过,我不认为这是最好的方法,因为您应该在 OnInit 中订阅路由参数以查找如下参数:

ngOnInit(){
this.routeParamsSub = this.route.params.subscribe(routeParams => {
this.blogId = routeParams['id'];

// do something else here
});
}

在这个 article 中可以看到类似的方法.

关于angular - activatedRoute 快照在 TS 类构造函数中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42900426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com