Mam mały problem z moją aplikacją Angular2. Chcę uzyskać dane z serwera dla mojego loginu użytkownika, ale mój kod idzie dalej i mam z tym wiele błędów. Chcę poczekać na odpowiedź od serwera, a następnie zrobić coś z moimi danymi.Oczekiwanie na odpowiedź z serwera na żądanie http w Angular 2
To jest mój kod:
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;
}
Jak zauważył mój kod będzie dla pętli, dopóki nie dostanę odpowiedź z serwera, więc wrócę tylko pustą tablicę. Czy ktoś może mi w tym pomóc?
Dziękuję bardzo, teraz wszystko wygląda dobrze;) – Celdur
:-) Byłoby wspaniale, gdybyś wznowił tę odpowiedź i oznaczył ją jako "rozwiązaną". Dzięki – Matt