Angular 2,post方法到本地json文件

时间:2017-05-02 10:31:43

标签: angular typescript post http-post angular2-http

我开始学习角度2,我想在json文件中添加一个新对象,但我总是有以下错误。

  

Failed to load resource: the server responded with a status of 405 (Method Not Allowed)

  zone.js:2164 POST http://localhost:50149/src/data.json 405 (Method Not Allowed)
   scheduleTask @   zone.js:2164
   ZoneDelegate.scheduleTask    @   zone.js:384
   onScheduleTask   @   zone.js:274
   ZoneDelegate.scheduleTask    @   zone.js:378
   Zone.scheduleTask    @   zone.js:209
   Zone.scheduleMacroTask   @   zone.js:232
   (anonymous)  @   zone.js:2188
   send @   VM45:3
   (anonymous)  @   http.umd.js:1229
   Observable.subscribe @   Observable.ts:98
   AppComponent.addb    @   app.component.ts:61
   View_AppComponent0.handleEvent_44    @   /AppModule/AppComponent/component.ngfactory.js:366
  (anonymous)   @   platform-browser.umd.js:3221
   ZoneDelegate.invokeTask  @   zone.js:398
   onInvokeTask @   core.umd.js:4426
   ZoneDelegate.invokeTask  @   zone.js:397
   Zone.runTask @   zone.js:165
   ZoneTask.invoke  @   zone.js:460

服务类:

 @Injectable()
export class AppServices {

    constructor(public http: Http){}

    headers = new Headers({

        'Content-Type': 'application/json',
        'Accept': 'application/json'     
    });

    public getJSON(): Observable<any> {
        return this.http.get("data.json")
            .map((res: any) => res.json())
            .catch((error: any) => console.log(error));
    }

    public add(body: any): Observable<any> {
        let options = new RequestOptions({
            method: RequestMethod.Post,
            headers: this.headers,
            body: JSON.stringify(body),
            url: "data.json"
        });
        return this.http.request(new Request(options))
    }
}

方法get没有给出任何错误,问题在于post和put方法,修改文件json的方法。

0 个答案:

没有答案