Angular2 - OnInit : Values returned from Service' subscribe function does not get assigned to Component field/s

后端 未结 2 529
北海茫月
北海茫月 2020-12-16 20:07

I\'m trying out Angular2 and have been following their tutorials.

I currently have a Service that gets data from a json server:



        
相关标签:
2条回答
  • 2020-12-16 20:23

    This is because this.getUsers() and then this.userService.getUsers().subscribe(...) only schedules a call to make a request to the server. Eventually when the response from the server arrives (console.log('ngOnit after getUsers() ' + this.users); was already executed before the call to the server was even made) then the function you passed to subscribe() is executed.

    This should do what you want:

      getUsers() {
        return this.userService
        .getUsers()
        .map(
          (users) => {
            console.log('users ' + users);
            this.users = users;
            console.log('this.users ' + this.users);
          })
         .catch((error) => {
            console.log('error ' + error);
            throw error;
          });
        // users => this.users = users,
        // error => this.errorMsg = <any>error);
      }
    
      ngOnInit() {
        this.getUsers().subscribe(_ => {;
          console.log('ngOnit after getUsers() ' + this.users);
        });
      }
    

    In getUsers() I use map() instead of subscribe, so we can subscribe later in order to be able to get code executed when the response arrived.

    Then in ngOnInit() we use the subscribe() (subscribe() is necessary, otherwise would http.get() would never be executed) and pass the code we want to be executed when the response arrives.

    I also changed function () to () =>. This way this works inside the following code block () => { ... }, otherwise it wouldn't.

    Don't forget to add

    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/catch';
    

    otherwise these operators won't be recoginzed.

    0 讨论(0)
  • 2020-12-16 20:25

    for me this is works like magic i was need to get data from api to initialize datatable component

    1- on your http service create normal get request like this :

      public get(url: string):Observable<any> {
        return this.http.get<any>( url );
       }
    

    2- on your component :

    constructor(private HttpSvc: HttpService) {}
    
      ngOnInit() {
        this.render();
      }    
    render() {
            let options = this.options || {};
              this.HttpSvc.Get('your api url').subscribe(data => {
                this.Tableset = data;
                options = {
                  data: this.Tableset.data,
                  columns: this.Tableset.columns,
                  dom: 'Bfrtip',
                  buttons: this.Tableset.buttons,
                  autoWidth: false,
                  pageLength: 2,
                  retrieve: true,
                  responsive: true
                };
              }, err => {console.log(err); },
              () => {
                this.renderDetails(options); //<-- can call any other method after call end
              });
        }
    

    here the full example link

    0 讨论(0)
提交回复
热议问题