HttpClient 在 RESTful API 上无法正常工作
HttpClient is not working properly on RESTful API
Delete 方法没有给我一个错误,因为我将 1000 作为参数传递,而该参数不存在于“https://jsonplaceholder.typicode.com/posts”json 文档中.相反,它只是删除选定的文档。我到处搜索,但没有找到任何指定如何解决此问题的代码。任何帮助将不胜感激,因为我是 Angular Framework 的新手。
下面是我的服务代码文件(post.service.ts)
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { catchError } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
import { NotFoundError } from '../common/not-found-error';
import { AppError } from '../common/app-error';
import { BadInput } from '../common/bad-input';
// For handling Http Requests
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class PostService {
private url = 'https://jsonplaceholder.typicode.com/posts';
private userUrl = 'https://jsonplaceholder.typicode.com/users';
constructor(private http: HttpClient) {}
getPosts() {
return this.http.get(this.url);
}
deletePost(id) {
console.log('Service Id: ', id);
return this.http.delete(this.url + '/' + id)
.pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 404) {
console.log('You screwed');
return throwError(new NotFoundError());
}
return throwError(new AppError(error));
})
);
这是我的组件文件(post.component.ts)
deletePost(post) {
console.log('Post Id is: ', post.id);
this.service.deletePost(1000)
.subscribe(
response => {
let index = this.posts.indexOf(post);
this.posts.splice(index, 1);
console.log(response);
},
(error: AppError) => {
if (error instanceof NotFoundError) {
alert('This post has already been deleted');
} else {
alert('An Unexpected error occurred.');
console.log(error);
}
});
}
ngOnInit() {
this.service.getPosts()
.subscribe((response) => {
this.posts = response;
console.log('Posts: ', this.posts);
}, error => {
alert('An Unexpected error occurred.');
console.log(error);
});
}
这是我的 Component.html 文件(posts.component.html)
<ul class="list-group">
<li *ngFor="let post of posts" class="list-group-item">
<button (click)="deletePost(post)" class="btn btn-danger btn-sm">Delete</button>{{ post.title }}
</li>
</ul>
<br>
您正在调用 returns JSONObject 的 API。不是错误。查看 API
的 POSTMAN 调用
。
由于这不是错误,因此不会执行 CatchError。
更新
由于没有错误,您的成功部分将执行。它采用现有 posts
数组中返回对象的索引。如果您将索引记录到控制台,您可以看到它将是 -1。
在不检查是否找到索引的情况下,您将其传递给拼接。
array.splice(-1,1)
将从数组中删除最后一个元素。因此 li
元素被删除。
更多关于Array.indexOf and Array.splice
您必须检查数组中是否存在返回对象的索引。然后进行拼接。
我正在使用这种方法,希望对您有所帮助。
(如果您 return 您的服务结果作为 Observable,那么从组件端管理它的结果会更容易。)
更新:
myService.ts
deleteDocumentService(documentId: number): Observable < any > {
var result: Observable < any > = this.http.delete < any > (`${this.apiBaseUrl}document/${documentId}`);
return result;
}
myComponenet.ts
import {myService} from './Services/myService'
deleteDataSubscription: Subscription;
data: any;
constructor(public _myService: myService) {}
//you will fire this function when button is clicked
deleteDocument(id:number) {
//call your delete service here
this.deleteDataSubscription = this._myService.deleteDocumentService(id)
.subscribe(
(success) => {
//if your delete operation is succesfully, do what ever you want here
//now you can fire a function or trigger to remove entry from your table
},
(error) => {
//if your delete operation is unsuccesfully, console log error.
console.log(err);
}
}
);
}
Delete 方法没有给我一个错误,因为我将 1000 作为参数传递,而该参数不存在于“https://jsonplaceholder.typicode.com/posts”json 文档中.相反,它只是删除选定的文档。我到处搜索,但没有找到任何指定如何解决此问题的代码。任何帮助将不胜感激,因为我是 Angular Framework 的新手。
下面是我的服务代码文件(post.service.ts)
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { catchError } from 'rxjs/operators';
import { Observable, throwError } from 'rxjs';
import { NotFoundError } from '../common/not-found-error';
import { AppError } from '../common/app-error';
import { BadInput } from '../common/bad-input';
// For handling Http Requests
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class PostService {
private url = 'https://jsonplaceholder.typicode.com/posts';
private userUrl = 'https://jsonplaceholder.typicode.com/users';
constructor(private http: HttpClient) {}
getPosts() {
return this.http.get(this.url);
}
deletePost(id) {
console.log('Service Id: ', id);
return this.http.delete(this.url + '/' + id)
.pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 404) {
console.log('You screwed');
return throwError(new NotFoundError());
}
return throwError(new AppError(error));
})
);
这是我的组件文件(post.component.ts)
deletePost(post) {
console.log('Post Id is: ', post.id);
this.service.deletePost(1000)
.subscribe(
response => {
let index = this.posts.indexOf(post);
this.posts.splice(index, 1);
console.log(response);
},
(error: AppError) => {
if (error instanceof NotFoundError) {
alert('This post has already been deleted');
} else {
alert('An Unexpected error occurred.');
console.log(error);
}
});
}
ngOnInit() {
this.service.getPosts()
.subscribe((response) => {
this.posts = response;
console.log('Posts: ', this.posts);
}, error => {
alert('An Unexpected error occurred.');
console.log(error);
});
}
这是我的 Component.html 文件(posts.component.html)
<ul class="list-group">
<li *ngFor="let post of posts" class="list-group-item">
<button (click)="deletePost(post)" class="btn btn-danger btn-sm">Delete</button>{{ post.title }}
</li>
</ul>
<br>
您正在调用 returns JSONObject 的 API。不是错误。查看 API
的 POSTMAN 调用由于这不是错误,因此不会执行 CatchError。
更新
由于没有错误,您的成功部分将执行。它采用现有 posts
数组中返回对象的索引。如果您将索引记录到控制台,您可以看到它将是 -1。
在不检查是否找到索引的情况下,您将其传递给拼接。
array.splice(-1,1)
将从数组中删除最后一个元素。因此 li
元素被删除。
更多关于Array.indexOf and Array.splice
您必须检查数组中是否存在返回对象的索引。然后进行拼接。
我正在使用这种方法,希望对您有所帮助。 (如果您 return 您的服务结果作为 Observable,那么从组件端管理它的结果会更容易。)
更新:
myService.ts
deleteDocumentService(documentId: number): Observable < any > {
var result: Observable < any > = this.http.delete < any > (`${this.apiBaseUrl}document/${documentId}`);
return result;
}
myComponenet.ts
import {myService} from './Services/myService'
deleteDataSubscription: Subscription;
data: any;
constructor(public _myService: myService) {}
//you will fire this function when button is clicked
deleteDocument(id:number) {
//call your delete service here
this.deleteDataSubscription = this._myService.deleteDocumentService(id)
.subscribe(
(success) => {
//if your delete operation is succesfully, do what ever you want here
//now you can fire a function or trigger to remove entry from your table
},
(error) => {
//if your delete operation is unsuccesfully, console log error.
console.log(err);
}
}
);
}