除非路由点击两次,否则不会调用ngOnInit并且组件不会加载

时间:2016-03-16 14:57:13

标签: angular angular2-directives angular2-services

My Home组件无法加载,除非我点击它的routerLink但它应该在应用程序启动时加载。

我的组件上有属性,这些属性嵌套在它的一侧,并在Home组件的加载时获取数据。

export class HomeComponent implements OnInit, OnDestroy {
   public subscription: Subscription;
   constructor(public router: Router, public userService:UserSettingsService, public safetyService: SafetyService) {
      var self = this;
      // Is called and data is loaded.
      self.loadDataForSafety(userService.defaultFilterObject);
      this.subscription = this.userService.filterObjectAnnounced$.subscribe(
          filtered => {
              self.selectedFilters = filtered;
              self.loadDataForSafety(self.selectedFilters);
          }
      );
   }

}

ngOnInit() {
  var self = this;
  this.subscription = this.userService.filterObjectAnnounced$.subscribe(
      filtered => {
          self.selectedFilters = filtered;
          self.loadDataForSafety(self.selectedFilters);
      }
  );
}

loadDataForSafety(filterObj) {
   var filterObj = filterObj;
   var self = this;
   var lowestDataLevel = 'RegionNum';
this.components.forEach(function(cardElem){
  if(cardElem.id == "safetyWidget"){
      self.safetyService.getAllSafetyElements(filterObj)
      .map(data => {
         // Itterate through array of objects returned
         Object.keys(cardElem.cardData).forEach(card => {
           var keyID = '';
           if(card == '3'){
             keyID = 'SBOWT';
           }else if(card == '2'){
             keyID = 'RWT';
           }else if(card == '4'){
             keyID = 'BHOIT';
           }else if(card == '0'){
             keyID = 'Backing';
           }
           data.forEach(elem =>{
             cardElem.cardData[card].push({
               "text": elem[lowestDataLevel],
               "id": elem[lowestDataLevel],
               "value": elem[keyID],
               "percent": (Math.random() * (99 - 20) + 20) + "%"
             });
           })
         })
         // DATA IS PRESENT
         return cardElem.cardData;
      })
      .subscribe(data => {
        // DATA IS PRESENT HERE
        cardElem["cardData"] = data;
      })
  }
})

}

构造函数已启动,但ngOnInit从未启动,因为组件未呈现。

也没有记录错误。

0 个答案:

没有答案