How to I load JSON data into Angular2 component

前端 未结 1 1479
旧时难觅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: `
        

    Hello from the {{ componentName }}!

    Name: {{ f.name }}

    Age: {{ f.age }}

    `

    0 讨论(0)
提交回复
热议问题