【问题标题】:ngOnInit called everytime i change route每次我更改路线时都会调用 ngOnInit
【发布时间】:2017-12-27 15:09:43
【问题描述】:

我有一个控制器实现 OnInit 这里的问题是每当我更改路线并返回相同的组件时,每次都会调用 ngOnInit。我做错了什么我无法理解。任何人请帮助我。

@Component({
    selector:'test-list',
    templateUrl:'./testlist.component.html',
    styles:[`.testname{
        text-transform : capitalize;
    }`]
})
export class TestListComponent implements OnInit{
    testList:Array<Test>;
    constructor(private testService:TestService,private router:Router){}
    ngOnInit(){
        this.testService.getTest()
        .subscribe(
            data=>this.testList = <Array<Test>>data,
            error=>alert(error)
        );
        console.log("ngInit")
    }
    editTest = (id)=>{
        this.router.navigate(['createtest',id]);
    }
}

【问题讨论】:

  • 不确定我是否理解您的问题,但这是预期的行为吗?您更改路由,然后返回组件是 TestListComponent 的新实例,因此需要调用 OnInit()
  • 它应该只被调用一次,因为我知道何时创建 TestListComponent 而不是每次我回到同一个组件时。我说的对吗?
  • 我认为我们回答得很好...It's a new instance every time component is called
  • 我认为 Vikram 你在这里感到困惑。 @12 秒的最后回复是 It should be called only once as i know when the TestListComponent is created not every time when i come back to same component. Am i right? 而不是 component is created every time when we change the route?
  • 1在 testService.getTest() 中,您是否将响应映射到 json 有效负载 as Array&lt;Test&gt;>data .... 外部 是必要的吗?如果你的返回类型是我建议的 this.testList = data 就足够了

标签: javascript angular


【解决方案1】:

ngOnInit() 每次加载组件时都会执行。它不需要被调用。这是一个用于做初始工作的生命周期钩子。您可以了解有关 Angular 生命周期钩子的更多信息 here

【讨论】:

    【解决方案2】:

    如果您在构造函数中订阅了活动路由,则每次路由器导航到该页面时都会调用 ngInit。

    constructor(
        private route: ActivatedRoute,
        private router: Router
    ) {
        this.route.queryParams.subscribe(async (params) => {
            if (this.router.getCurrentNavigation().extras.state) {
                // TODO save the params
            }
        });
    }
    
    ngOnInit(){
        console.log('ngOnInit called');
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-13
      • 2019-07-21
      • 1970-01-01
      • 2018-08-08
      • 2016-05-26
      • 2018-06-13
      • 1970-01-01
      • 2022-01-02
      相关资源
      最近更新 更多