【发布时间】: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<Test>?>data .... 外部 是必要的吗?如果你的返回类型是我建议的 this.testList = data 就足够了
标签: javascript angular