【发布时间】:2018-01-11 05:32:09
【问题描述】:
我正在尝试使用角度服务从数据库中获取用户。在服务中执行 GET 请求时,我可以console.log(res) 并获得响应。但是,当我尝试从另一个组件中获取数据时,它总是出现undefined。请帮忙。
users.service.ts
import { Injectable } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpClient, HttpClientModule } from '@angular/common/http';
@Injectable()
export class UsersService {
constructor(
private http: HttpClient,
private route: ActivatedRoute
) { }
users: any;
getUsers() {
this.http.get('http://localhost:3000/api/users').subscribe(res => {
this.users = res;
return this.users;
});
}
}
app.component.ts
import { UsersService } from './users.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
providers: [ UsersService ]
})
constructor(
private http: HttpClient,
private route: ActivatedRoute,
private usersService: UsersService
) {
this.users = usersService.getUsers();
}
当我尝试在 app.component.html 中使用它时...
<div *ngFor="let user of users"></div>
用户出现未定义
【问题讨论】: