本文介绍了每当我更改路线时都会调用ngOnInit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器实现OnInit这里的问题是,每当我更改路线并返回相同组件时,每次都会调用ngOnInit.我做错了我不明白的事.任何人都可以帮助我.

I have a controller implements OnInitThe problem here is whenever i change the route and come back to same component ngOnInit is called everytime. What i am doing wrong i am not able to understand.Anybody please help me.

@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]);
    }
}

每次加载组件时,都会执行

推荐答案

ngOnInit().不需要调用.这是执行初始任务的生命周期挂钩.您可以了解有关角度生命周期挂钩的更多信息此处

ngOnInit() is executed everytime the component is loaded. It doesn't need to be called. This is a lifecycle hook for doing initial stuff. You can learn more about angular lifecycle hookshere

这篇关于每当我更改路线时都会调用ngOnInit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 14:01