Renê Silva Lima
Renê Silva Lima

Reputation: 2815

Http Post on a Json file not working

Im trying to make a simple post on a json file on Angular, I called the service but it does not return anything on console neither on the network, am I missing something?

this is the snippet from the service:

import { Injectable } from '@angular/core';
import {HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http'

import { Observable } from 'rxjs/Observable';

export interface Todo {
  text: string
}

@Injectable()
export class TodoService {

  constructor(private http: HttpClient) { }

  addTodo(todo): Observable<Todo> {
    const newTodo = {
      text: todo.text
    }
    return this.http.post<Todo>('./assets/data/todo.json', newTodo);
  } 

When I click on a button it calls this addTodo function, however it does not return me anything.

And yes, there is a file called todo.json inside the assets folder. Is it possible to make a simple HTTP post on a json file?

Upvotes: 0

Views: 3760

Answers (2)

Arjun Panicker
Arjun Panicker

Reputation: 740

You cannot post to a Json file in assets folder directly. A web browser only supports GET calls to the files. To make the http.post working, you will have to use a web server to host the files .

One such web server which you can use easily is json server. It is available as an npm package. Use the json server to host your files and then use the URL provided by the json server to post the data. Read the docs for more understanding.

Upvotes: 3

thatcoder
thatcoder

Reputation: 367

Try this one. In your code, you are not passing the options header with the post call.

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';

export interface Todo {
    text: string
}

@Injectable()
export class TodoService {
    headers: Headers;
    options: RequestOptions;
    constructor(private http: Http) { 
       this.headers = new Headers({ 'Content-Type': 'application/json'});
       this.options = new RequestOptions({ headers: this.headers });
    }

    addTodo(todo): Observable<Todo> {
        const newTodo = {
        text: todo.text
    }
    return this.http.post<Todo>('./assets/data/todo.json', newTodo,this.options);
  } 

Upvotes: 0

Related Questions