Alturistic Alturistic - 1 year ago 90
TypeScript Question

How to get async data which is stored in the service?

I'm fetching data from http, store it inside the same service in an array.

export class UserService {
myusers: User[];
constructor(private http: HttpClient) {}
getUsers () {
return this.http.get<User[]>('https://randomuser.me/api/results=5')
.subscribe( data => { this.myusers = data['results']}); }
}


When I console myusers in component.ts it prints 'Undefined'.

export class UserComponent implements OnInit {
constructor(private service: UserService) { }
ngOnInit() {
this.service.getUsers();
console.log(this.service.myusers); //undefined
}
}


So how can I access the
this.service.myusers
? Dont suggest the solution which stores the data in component's array not in service myusers array.

rex rex
Answer Source

As returning data from API takes a bit time, so you need a callback from your service regarding completion of the job.

export class UserService {
    myusers: User[];
    constructor(private http: HttpClient) {}
    getUsers () {
        return this.http.get<User[]>('https://randomuser.me/api/results=5');
    }
    setUsers (users: User[]) {
        this.myusers = users;
    }
}

Call the function like below :

export class UserComponent implements OnInit {
  constructor(private service: UserService) { }
  ngOnInit() {
    this.service.getUsers()
    .subscribe( data => { this.service.setUsers(data); console.log(data); });
  }
}

Let me know if this doesn't serve your purpose

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download