每当我更改路线时都会调用ngOnInit [英] ngOnInit called everytime i change route

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

问题描述

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

I have a controller implements OnInit The 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 hooks here

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

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆