Angular4: how do access local json?

前端 未结 7 2206
傲寒
傲寒 2020-12-06 05:00

In Angular2 you could have a folder /data/ and a json file there and you could access it at localhost:4200/data/something.json.

This is no longer possible in Angular

7条回答
  •  死守一世寂寞
    2020-12-06 05:41

    you can use this code

    @Injectable()
    export class AppServices{
    
        constructor(private http: Http) {
             var obj;
             this.getJSON().subscribe(data => obj=data, error => console.log(error));
        }
    
        public getJSON(): Observable {
             return this.http.get("./file.json")
                             .map((res:any) => res.json())
                             .catch((error:any) => console.log(error));
    
         }
    }
    

    here file.json is your local json file.

    see here also

    • How to get a json file in angular2 using the Http class

    also see the changlog of angular-cli for path

    • https://github.com/angular/angular-cli/blob/master/CHANGELOG.md#100-rc4-2017-03-20

提交回复
热议问题