我试图有一个组件表示一个项目模型。此组件获取项目,然后显示它。我正在尝试使用幼童组件来获取项的其他属性并显示它们。不幸的是,这会导致递归调用Lifecycle.tick()。
以下列例子为例:
@Component{selector: 'comp2', properties: ['item']}
@View{template: '<ul *ng-if="fetchedAttributes != null"><li *ng-for="#attribute of fetchedAttributes"> {{ attribute.name }} </li></ul>',
directives: [NgIf, NgFor]}
export class Comp2 implements OnInit {
fetchedAttributes: null;
item: Item;
onInit() {
this.fetchAttributesPromise(this.item)
.then((attributes)=>{this.fetchedAttribues = attributes;});
}
}
@Component{selector: 'comp1'}
@View{template: '<comp2 *ng-if="fetchedItem != null" [item]="fetchedItem"></comp2>',
directives: [Comp2, NgIf]}
export class Comp1 {
fetchedItem: Item;
constructor() {
this.doFetchItem();
}
doFetchItem() {
this.doFetchPromise()
.then((item)=>{this.fetchedItem = item;});
}
}Comp1获取该项。当获取结果时,创建一个新的Comp2实例,它的item属性绑定到获取的项实例,并调用它的onInit钩子。这反过来会创建另一个请求来获取项属性,这会导致异常:
EXCEPTION: LifeCycle.tick is called recursively
Error: LifeCycle.tick is called recursively
at new BaseException (angular2.js:4688)
at execute.LifeCycle.tick (angular2.js:8741)
at angular2.js:8736
at Zone.run (zone.js?v=0.0.0:113)
at Zone.execute.$__5._createInnerZone.zone.fork.fork.$run [as run] (angular2.js:9041)
at XMLHttpRequest.zoneBoundFn (zone.js?v=0.0.0:86)如何在不遇到此问题的情况下跨多个组件级联请求?
发布于 2015-09-25 08:55:56
解决方案是使用服务来执行所有请求。如果视图绑定中注入视图范围的服务实例,则可以拥有该实例:
@Component({
//...
bindings: ['MyViewScopedService']
})在这种情况下,该服务将对所有查看子视图可用。
或者,如果您在引导应用程序时绑定应用程序范围内的服务实例,则可以:
bootstrap(App, [
MyAppScopedService,
//...
]);要使用它,请将其插入构造函数中:
class ServiceConsumer {
constructor(myService: MyViewScopedService) {
}
}然后在您的服务中级联请求。
https://stackoverflow.com/questions/32715154
复制相似问题