我正在从 http 获取数据,将其存储在数组中的同一服务中。
export class UserService {
myusers: User[];
constructor(private http: HttpClient) {}
getUsers () {
return this.http.get<User[]>('https://randomuser.me/api/results=5')
.subscribe( data => { this.myusers = data['results']}); }
}
当我在 component.ts 中控制台我的用户时,它会打印“未定义”。
export class UserComponent implements OnInit {
constructor(private service: UserService) { }
ngOnInit() {
this.service.getUsers();
console.log(this.service.myusers); //undefined
}
}
那么我怎样才能访问this.service.myusers
?不要建议将数据存储在组件数组而不是服务 myusers 数组中的解决方案。