How to I load JSON data into Angular2 component

前端 未结 1 1473
旧时难觅i
旧时难觅i 2020-12-28 11:54

After running through many tutorials on tinterweb I have finally started to try and build something useful to me using Angular2 and I have come across my first issue. I can

相关标签:
1条回答
  • 2020-12-28 12:21

    In fact, it's because your data are loaded asynchronously. So within the constructor of your component, you initially get an undefined value.

    constructor(private _friendService: FriendService) {
      this.friends = _friendService.getFriends();
    }
    

    To keep your constructor like that, you need to refactor your code to make the getFriends method of your service return an observable:

    @Injectable()
    export class FriendService { 
      constructor(private http:Http) {
      }
    
      getFriends() {
        return this.http.request('./data/people.json')
                     .map(res => res.json());
      }
    }
    

    Then you can use the async pipe into your component template:

    template: `
        <h1>Hello from the {{ componentName }}!</h1>
        <div *ngFor="#f of friends | async">
            <h3>Name: {{ f.name }}</h3> 
            <h4>Age: {{ f.age }}</h4> 
        </div>
    `
    
    0 讨论(0)
提交回复
热议问题