Angular 2 - undefinded when sharing a variable with API data between a component

Basically, what I'm trying to do is hit my API once and save the result inside a global variable in my service, and then share and change that value in the parent and child components using two helper functions.

repairs.service.ts

public myItems:any[];

   public GetRepairs = ():Observable<any> => {

     this.headers = new Headers();
     this.headers.set('Authorization', 'Bearer' + ' ' + JSON.parse(window.localStorage.getItem('token')));

      return this._http.get(this.actionUrl +'repairs'{headers:this.headers})
              .map((res) => {return res.json();
                }).map((item) => {
                    let result:Array<any> = [];
                    if (item.items) {
                        item.items.forEach((item) => {
                            result.push(item);
                        });
                    }

                    this.myItems = result;
                    return this.myItems;
             });
    };

    public GetItems() {
       return this.myItems;
    };

    public UpdateItems(data:any[]) {
       this.myItems = data;
    };

And then in my main component I do

repairs.component.ts

export class RepairsComponent implements OnInit {
    public myItems:any[];

    constructor(private _userService:UserService,
                private _RepairsService:RepairsService,
                public _GlobalService:GlobalService) {
    }

    ngOnInit() {
        this._userService.userAuthenticate();
        this.getAllItems();
    }

    private getAllItems():void {
        this._RepairsService
            .GetRepairs()
            .subscribe((data) => {
                    this._RepairsService.UpdateItems(data);
                },
                error => console.log(error),
                () => {
                    this.myItems = this._RepairsService.GetItems();
                });
          }
   }

This work is fine, but when I try to call GetItems () on a child component, I get undefinded. I am trying to do this inside the constructor and ngOnInit with the same result.

child.component.ts

export class ChildComponent {
    private items:any[] = [];


    constructor(private _RepairsService:RepairsService, 
                private _Configuration:Configuration) {
        this.items = this._RepairsService.GetItems();
        // undefinded
    }


    ngOnInit() {
        this.items = this._RepairsService.GetItems();
        // undefinded
    }
}
+4
source share
3

, , , , , http get call . , GetItems() , , , http get, , .

+2

@MSwehli, , . :

ngOnInit() {
    this.items = this._RepairsService.GetItems();
    // undefinded
}

GetItems(); , . , , . .

Promise, .then(...) , .

+2

/:

  • userAuthenticate(), getAllItems(). , getAllItems(), getAllItems .

rxjs flatMap:

//assuming userAuthenticate returns Observable
userService.userAuthenticate().flatMap(()=>{
    return repairsService.GetRepairs();
}).subscribe(..process repairs..);
  1. getAllItems () is called almost simultaneously with GetItems (). In most cases, it also does not work, since the previous HTTP request does not complete when GetItems () is called.

In my opinion, early initialization is not needed here, use the service directly:

//ChildComponent
ngOnInit() {
    this._RepairsService.GetRepairs().subscribe(..do anything with list of repairs i.e. assign to bindable property..);
}

You can add console.log instructions in each piece of code to see the order of events in your application.

0
source

All Articles