在httmclient方法Angular中读取json文件

时间:2019-06-22 23:53:30

标签: angular observable httpclient

我有一个小问题,我想在我的html页面中显示数据,我在此服务中使用一个服务,我这样使用httpclient:http.get(“ ./ users.json”)但它不起作用,我有一个错误,我该如何解决该错误,Thnaks fo回答:)

enter image description here

user.service.ts

getUsers() : Observable<User[]> {
    return this.http.get("./users.json").pipe(map(data=>{
        let usersList = data["userList"];
        return usersList.map(function(user:any) {
            return {name: user.userName, age: user.userAge};
        });
    }));
}

user.component.ts

users: User[] = [];
constructor(private userService: UserService){}
ngOnInit(){
   this.userService.getUsers().subscribe(data => this.users=data);
}

user.component.html

<li *ngFor="let user of users">
   <p>Name: {{user?.name}}</p>
   <p>Age: {{user?.age}}</p>
</li>

1 个答案:

答案 0 :(得分:0)

关于链接:将文件放在资产文件夹下,然后尝试以下代码:

return this.http.get<any>('assets/users.json')