HttpClient在RESTful API上无法正常工作

时间:2019-02-28 09:11:07

标签: angular rest angular6 angular-httpclient

删除方法没有给我一个错误,因为我将 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>

2 个答案:

答案 0 :(得分:0)

您要调用的API返回JSONObject。没错。请参阅API的POSTMAN调用

POSTMAN invokation of the API

由于这不是错误,所以不会执行CatchError。

更新
由于没有错误,因此成功部分将执行。它获取现有posts数组中返回对象的索引。如果将索引记录到控制台,您将看到它为-1。
无需检查是否找到索引,就可以将其传递给接头。 array.splice(-1,1)将删除数组中的最后一个元素。因此li 元素将被删除。

有关Array.indexOfArray.splice的更多信息

您必须检查数组中是否存在返回对象的索引。然后进行拼接。

答案 1 :(得分:0)

我正在使用这种方法,希望对您有所帮助。 (如果您将服务结果返回为Observable,则从组件端管理结果更加容易。)

更新:

myService.ts

int main()
{
    Game Game1;
    Player A(0, "Player1");
    Player B(1, "Player2");
    Game1.addPlayer(A);

    Game1.addPlayer(B);

    cout << "Name is:" << Game1.nameList[1] << "\n";



    cout << "Name is:" << Game1.playerList[1]->getName() << "\n";






    return 0;

}

myComponenet.ts

deleteDocumentService(documentId: number): Observable < any > {
    var result: Observable < any > = this.http.delete < any > (`${this.apiBaseUrl}document/${documentId}`);
    return result;
}