【问题标题】:httpClient put request display errorhttpClient put 请求显示错误
【发布时间】:2018-08-26 14:22:13
【问题描述】:

我想更新一些数据,例如我使用来自互联网的免费 api。

我的浏览器出现以下错误:

有什么问题?

  updateShortUrl(data: ShortUrl): Observable<any> {
     return this._http.put('https://jsonplaceholder.typicode.com/posts/1').pipe(map((res) => {
      return res;
    }));

  }

我的导入看起来像:

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { HttpClient, HttpParams } from '@angular/common/http';
import { map } from 'rxjs-compat/operator/map';
import { map, Observable } from 'rxjs/operators';
import 'rxjs/add/operator/delay';
import 'rxjs/add/operator/switchMap';

【问题讨论】:

    标签: angular rxjs angular-httpclient


    【解决方案1】:

    问题是您正在使用 POST 请求,并且在发布请求时需要发送多个参数。如果您注意到您正在将参数传递给 updateShortUrl 方法,但您也从未使用过它。

    updateShortUrl(data: ShortUrl): Observable<any> {
         return this._http.put('https://jsonplaceholder.typicode.com/posts/1', YOUR_PARAMETER_HERE).pipe(map((res) => {
          return res;
        }));   
      }
    

    另外,请记住使用“任何”不是一个好习惯。通过您使用 .pipe 将始终返回一个可观察的,因此无需通过放置任何重复自己。另一件事是,如果您对返回的请求不做任何事情,则不需要使用管道。你可以有这样的东西:

    updateShortUrl(data: ShortUrl) {
             return this._http.put('https://jsonplaceholder.typicode.com/posts/1', YOUR_PARAMETER_HERE);
          }
    

    最好的做法是创建一个模块来指定你得到的 Observable 的种类

    export class Post {
         userId: number,
         id: number,
         title: string,
         body: string
    
         constructor(private userId: number, private id: number, private title: , private body: string) {
          this.userId= userId;
          this.id= id;
          this.title = title
          this.body = body
         }
    }
    

    你使用它的方式如下:

    updateShortUrl(data: ShortUrl) Observable<Post> {
       return this._http.put('https://jsonplaceholder.typicode.com/posts/1', YOUR_PARAMETER_HERE);
    }
    

    另外,我注意到您正在使用该 jsonplaceholder 来测试您的应用程序。您始终可以使用 JSON-SERVER https://www.npmjs.com/package/json-server

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-14
      • 2019-11-01
      • 1970-01-01
      相关资源
      最近更新 更多