我正在尝试使用角度服务从数据库中获取用户。在服务中执行 GET 请求时,我可以console.log(res)
并得到回应。但是,当我尝试从另一个组件获取数据时,它总是出现undefined
。请帮忙。
用户.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;
});
}
}
应用程序组件.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>
用户未定义
如果您使用服务来集中用户数据,请考虑以下内容:
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 时(第一次出现在提供程序数组中)时被调用,并且您的用户数据将可供注入 UsersService 的任何组件使用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)