Angular服务-GET返回未定义 [英] Angular service - GET returns undefined
问题描述
我正在尝试使用角度服务从数据库中获取用户.在服务中执行GET请求时,我可以console.log(res)
并获取响应.但是,当我尝试从另一个组件获取数据时,它总是出现在undefined
上.请帮忙.
I'm trying to use an angular service to get users from a database. When doing a GET request IN the service, I can console.log(res)
and get the response. However, when I try to grab the data from another component, it always comes up undefined
. Please help.
users.service.ts
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
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中使用它时...
And when I try to use it in app.component.html ...
<div *ngFor="let user of users"></div>
用户出现未定义状态
推荐答案
如果您正在使用服务来集中用户数据,请考虑以下事项:
If you are using your service to centralize your users data, then consider this:
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
) {
this.getUsers()
.subscribe(data => this.users = data);
}
users: any;
getUsers() {
return this.http.get('http://localhost:3000/api/users');
}
}
然后在您的组件中:
constructor(
private http: HttpClient,
private route: ActivatedRoute,
public usersService: UsersService <------ changed to public to make it available to the template
) {
// this.users = usersService.getUsers(); <------ commented out, as users is now centralized in the service
}
并在您的模板中:
<div *ngFor="let user of usersService.users"></div>
通过进行这些更改,您的getUsers()方法将仅在创建UsersService时(首次出现在providers数组中)被调用,并且您的用户数据将可用于任何注入UsersService的组件.
By making these changes, your getUsers() method will only be called at the creation time of your UsersService (first time it appears in providers array) and your users data will be available to any component that injects UsersService.
这篇关于Angular服务-GET返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!