在 angular 中实施 post 方法后出现“net::ERR_INTERNET_DISCONNECTED”错误
I am getting " net::ERR_INTERNET_DISCONNECTED" error after implementing post method in angular
这是我的代码。
这是服务代码,我在其中为 post 方法
创建了一个方法
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));
}
}
我调用服务的组件代码
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);
});
}
}
[这是我收到的错误图片]([1]: https://i.stack.imgur.com/psfQ5.jpg)
当我尝试使用本地 json 服务器仍然收到此错误时,对象已 post 在数据库中成功编辑。
你可以试试这个,对我有用
getPosts(parameter) {
return this.http.post<any>(this.url, parameter);
}
这是我的代码。 这是服务代码,我在其中为 post 方法
创建了一个方法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));
}
}
我调用服务的组件代码
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);
});
}
}
[这是我收到的错误图片]([1]: https://i.stack.imgur.com/psfQ5.jpg)
当我尝试使用本地 json 服务器仍然收到此错误时,对象已 post 在数据库中成功编辑。
你可以试试这个,对我有用
getPosts(parameter) {
return this.http.post<any>(this.url, parameter);
}