0

I know the question title is very general so I'll give the details.

Component:

export class MaterialDetailComponent implements OnInit {
  originalMaterialsData: Material[];
  currentMaterialData: Material[];

  constructor(private _route: ActivatedRoute, public dataService:DataService) { }

  ngOnInit() {
    let id = +this._route.snapshot.paramMap.get('id');

    this.dataService.getMaterialData().subscribe((response) => {
      this.originalMaterialsData = response;
    });

    for(let i = 0; i < this.originalMaterialsData.length; i++) {
      if(this.originalMaterialsData[i].id = id) {
        this.currentMaterialData.push(this.originalMaterialsData[i]);
      }
    }

  }


}

I'm trying to get the matched object with an id from originalMaterialsData (array of objects) and assign it to currentMaterialData so that I'm able to use this one particular object in my component. But it keeps returning undefined even though I tried many ways to differently write it.

  • Did you try to put the `for`-loop into your `subscribe` block? – Stephan Strate Mar 06 '18 at 14:10
  • It is because getMaterialData() is async. So your code first goes in the for loop before it gets the data – fawee Mar 06 '18 at 14:12
  • Also [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](//stackoverflow.com/q/23667086) and [Waiting for an observable to finish](//stackoverflow.com/q/43366694) – Heretic Monkey Mar 06 '18 at 14:14
  • That's right. I totally forgot that my function was async. I made that part async as well and it works! Thanks @StephanStrate and fawee – Ahmet Ömer Mar 06 '18 at 14:52

0 Answers0