This is My Code. This is Service Code in which I created a method for post method
Service Code
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
export interface Obj {
userId?: number,
title?: string,
body?:string
}
@Injectable({
providedIn: 'root'
})
export class ServiceService {
url ='https://jsonplaceholder.typicode.com/posts'
constructor(private http:HttpClient) {
}
getPosts():Observable<Obj[]>{
return this.http.get<Obj[]>(this.url)
}
createPost(fData:Obj){
return this.http.post<Obj>(this.url,(fData));
}
}
This Component Code where I called the service
Component Code[enter image description here][1]
import { Obj } from './../service.service';
import { Component, OnInit } from '@angular/core';
import { ServiceService } from '../service.service';
@Component({
selector: 'post',
templateUrl: './post.component.html',
styleUrls: ['./post.component.css']
})
export class PostComponent {
posts: Obj[] = [] ;
constructor(private httpService:ServiceService){
}
ngOnInit(): void{
this.httpService.getPosts().subscribe(response=>{
this.posts = response;
console.log(this.posts)});
}
addUser(data:HTMLInputElement){
this.httpService.createPost(data).subscribe((response)=> {
console.log(response);
});
}
}
[Here is the image of the error I am Getting]([1]: https://i.sstatic.net/psfQ5.jpg)
The Object is posted successfully in database when I try with local json server still getting this error.
you can try this, it's worked for me
getPosts(parameter) {
return this.http.post<any>(this.url, parameter);
}