Load json from local file with http.get() in angular 2

前端 未结 7 1116
情歌与酒
情歌与酒 2020-11-29 00:38

I\'m trying to load a local json with http.get() in angular 2. I tried something, that I found here on stack. It looks like this:

this is my app.m

7条回答
  •  遥遥无期
    2020-11-29 01:24

    You have to change

    loadNavItems() {
            this.navItems = this.http.get("../data/navItems.json");
            console.log(this.navItems);
        }
    

    for

    loadNavItems() {
            this.navItems = this.http.get("../data/navItems.json")
                            .map(res => res.json())
                            .do(data => console.log(data));
                            //This is optional, you can remove the last line 
                            // if you don't want to log loaded json in 
                            // console.
        }
    

    Because this.http.get returns an Observable and you don't want the response, you want its content.

    The console.log shows you an observable, which is correct because navItems contains an Observable.

    In order to get data properly in your template, you should use async pipe.

    
    

    This should work well, for more informations, please refer to HTTP Client documentation

提交回复
热议问题