Почему нельзя перебрать массив в моей модели с помощью функции map () - PullRequest
0 голосов
/ 14 февраля 2019

У меня есть угловой компонент 7, который привязан к модели, и внутри этой модели есть массив, который был заполнен сервисом.и он заполнен.

проблема в том, что я не могу отобразить массив, хотя там есть элементы.когда я утешаю его, это показывает, что массив имеет элемент.затем я попытался утешить typeOf (массив), он всегда дает объект, хотя это массив !!.

я пытался использовать это решение , но это тоже не помогло.

любая помощь, пожалуйста?

 export class FooModel {  
   foo : Foo  
   bars: Bar[];
 }

export class SomeComponent implements OnInit {
   model: FooModel;

   constructor(private service: ProjectService) {
    this.model = new FooModel();
    this.model.bars = [];
   } 

   ngOnInit() {
     this.service.getFoos().subscribe((result: any) => {
     // data is populated fine
     this.model=  <FooModel>result.data; 
     });

     Console.log(this.model); // the model has data at this point

     const arr = this.model.bars.map(a=> {
        // never comes here
        return a;
     });

     console.log(arr); // nothing is displayed here

    // this works why ??
    const arr2 = [1,2,3].map(s=> {
        return s;
    }
    console.log(arr2); // it displays [1,2,3]
   }
}

Ответы [ 3 ]

0 голосов
/ 14 февраля 2019

подписка является асинхронной, поэтому, пока она все еще работает, следующая операция строки в стеке выполнения будет выполняться, в этом случае карта, имеющаяся у вас после подписки, в то время как она все еще заполняется в фоновом режиме.Вы можете попробовать сопоставить в другом хуке жизненного цикла, скажем, viewChecked, надеюсь, это сработает.# веселит

0 голосов
/ 14 февраля 2019

Пожалуйста, посмотрите на комментарии

 export class FooModel {  
       foo : Foo  
       bars: Bar[];
     }

    export class SomeComponent implements OnInit {
       model: FooModel;

       constructor(private service: ProjectService) {
        this.model = new FooModel();
        this.model.bars = [];
       } 

       ngOnInit() {
         this.service.getFoos().subscribe((result: any) => {
         // data is populated fine
         this.model=  <FooModel>result.data; 
         });
        // the following starts to execute even before the model is populated above.
         const arr = this.model.bars.map(a=> {
            // never comes here because this.model.bars is empty at here and the length is 0 and nothing inside map executes
            return a;
         });

         console.log(arr); // nothing is displayed here because it has nothing inside

        // this works why ?? because you are using on an array which has some items.
        const arr2 = [1,2,3].map(s=> {
            return s;
        }
        console.log(arr2); // it displays [1,2,3]
       }
    }

Итак, как предположил Саджитхарен, вы должны держать его внутри subscribe()

0 голосов
/ 14 февраля 2019

Поскольку запрос асинхронный, вам может потребоваться поместить логику в подписку,

this.service.getFoos().subscribe((result: any) => {
     // data is populated fine
     this.model=  <FooModel>result.data; 
      const arr = this.model.bars.map(a=> {
        // never comes here
        return a;
     });
     console.log(arr);
});
...