首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Lifecycle.tick递归调用

Lifecycle.tick递归调用
EN

Stack Overflow用户
提问于 2015-09-22 11:01:29
回答 1查看 1.2K关注 0票数 2

我试图有一个组件表示一个项目模型。此组件获取项目,然后显示它。我正在尝试使用幼童组件来获取项的其他属性并显示它们。不幸的是,这会导致递归调用Lifecycle.tick()

以下列例子为例:

代码语言:javascript
复制
@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钩子。这反过来会创建另一个请求来获取项属性,这会导致异常:

代码语言:javascript
复制
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)

如何在不遇到此问题的情况下跨多个组件级联请求?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-25 08:55:56

解决方案是使用服务来执行所有请求。如果视图绑定中注入视图范围的服务实例,则可以拥有该实例:

代码语言:javascript
复制
@Component({
//...
bindings: ['MyViewScopedService']
})

在这种情况下,该服务将对所有查看子视图可用。

或者,如果您在引导应用程序时绑定应用程序范围内的服务实例,则可以:

代码语言:javascript
复制
bootstrap(App, [
    MyAppScopedService,
    //...
]);

要使用它,请将其插入构造函数中:

代码语言:javascript
复制
class ServiceConsumer {
 constructor(myService: MyViewScopedService) {
 }
}

然后在您的服务中级联请求。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32715154

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档