I have a little problem with my Angular2 app. I want to get some data from server for my user login, but my code is going ahead and I have a lot of bugs with it. I want to wait for answer from server, then do something with my data.
This is my code:
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { User } from './user';
@Injectable()
export class UserService {
public usersTmp: Array<Object> = new Array<Object>();
public users: Array<User>;
public user: User = new User();
public noteToSend;
constructor(private http: Http) { }
getUsers() {
var headers = new Headers();
headers.append('Accept', 'q=0.8;application/json;q=0.9');
this.http.get('/AngularApp/api/users', { headers: headers })
.map((res: Response) => res.json())
.subscribe(
data => {
console.log(data);
this.usersTmp = data;
},
err => console.error(err),
() => console.log('done')
);
this.users = new Array<User>();
for (var i = 0; i < this.usersTmp.length; i++) {
this.user = new User();
this.user.id = this.usersTmp[i]["userId"];
this.user.name = this.usersTmp[i]["userName"];
this.user.email = this.usersTmp[i]["userEmail"];
this.user.pass = this.usersTmp[i]["userPassword"];
this.users.push(this.user);
}
return this.users;
}
As I noticed my code is going to the for loop until I get answer from server, so I return just empty array. Anyone can help me with that?
Use . toPromise on your observable followed by async/await .
HttpClient methods return one valuelink All HttpClient methods return an RxJS Observable of something. HTTP is a request/response protocol. You make a request, it returns a single response.
response : interceptors get called with http response object. The function is free to modify the response object or create a new one. The function needs to return the response object directly, or as a promise containing the response or a new response object.
In the service, you should return the Observable
that your component can subscribe to. It cannot work they way you do it due to the asynchronous mode of the get
request.
As a proposal, your service could look similar to this
getUsers() {
let headers = new Headers();
headers.append('Accept', 'q=0.8;application/json;q=0.9');
return this.http.get('/AngularApp/api/users', { headers: headers })
.map((res: Response) => res.json());
}
And the relevant part of your component like this:
constructor(private userService:UserService) {
this.userService.getUsers().subscribe(
data => this.iterateOverUsers(data));
}
iterateOverUsers(data) {
// here comes your for loop
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With