【问题标题】:Argument of type 'Request' is not assignable to parameter of type 'HttpRequest<any>''Request' 类型的参数不可分配给 'HttpRequest<any>' 类型的参数
【发布时间】:2018-10-23 06:02:53
【问题描述】:

我是新来的。请温柔,说外行。

在以下打字稿代码中,我的方法 sendRequest() 中出现此错误...

“Request”类型的参数不能分配给“HttpRequest”类型的参数。 “请求”类型中缺少属性“正文”。


我附上了邮件的图片。请问有人知道如何解决这个问题吗?谷歌运气不好。

import { Movie } from "./movie.model";
import { Injectable } from '@angular/core';
import { RequestMethod, Request, Response } from '@angular/http';
import { HttpClient } from '@angular/common/http';
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/map";
import { Filter } from "./configClasses.repository";
import { Studio } from "./studio.model";

const studiosUrl = "/api/studios";
const moviesUrl = "/api/movies";

@Injectable()
export class Repository {
    private filterObject = new Filter();
    private movieData: Movie;

    constructor(private http: HttpClient) {
        //this.filter.category = "drama";
        this.filter.related = true;
        this.getMovies(true);
    }

    getMovie(id: number) {
        this.sendRequest(RequestMethod.Get, moviesUrl + "/" + id)
            .subscribe(response => { this.movie = response.json(); });
        //console.log("Movie Data Requested");
    }

    getMovies(related = false) {
        let url = moviesUrl + "?related=" + this.filter.related;
        if (this.filter.category) {
            url += "&category=" + this.filter.category;
        }
        if (this.filter.search) {
            url += "&search=" + this.filter.search;
        }
        this.sendRequest(RequestMethod.Get, url)
            .subscribe(response => this.movies = response);
    }

    getStudios() {
        this.sendRequest(RequestMethod.Get, studiosUrl)
            .subscribe(response => this.studios = response);
    }
    createMovie(mov: Movie) {
        let data = {
            name: mov.name, category: mov.category,
            description: mov.description, price: mov.price,
            studio: mov.studio ? mov.studio.studioId : 0
        };
        this.sendRequest(RequestMethod.Post, moviesUrl, data)
            .subscribe(response => {
                mov.movieId = response;
                this.movies.push(mov);
            });
    }
    createMovieAndStudio(mov: Movie, stu: Studio) {
        let data = {
            name: stu.name, city: stu.city, state: stu.state
        };
        this.sendRequest(RequestMethod.Post, studiosUrl, data)
            .subscribe(response => {
                stu.studioId = response;
                mov.studio = stu;
                this.studios.push(stu);
                if (mov != null) {
                    this.createMovie(mov);
                }
            });
    }

    replaceMovie(mov: Movie) {
        let data = {
            name: mov.name, category: mov.category,
            description: mov.description, price: mov.price,
            studio: mov.studio ? mov.studio.studioId : 0
        };
        this.sendRequest(RequestMethod.Put, moviesUrl + "/" + mov.movieId, data)
            .subscribe(response => this.getMovies());
    }
    replaceStudio(stu: Studio) {
        let data = {
            name: stu.name, city: stu.city, state: stu.state
        };
        this.sendRequest(RequestMethod.Put,
            studiosUrl + "/" + stu.studioId, data)
            .subscribe(response => this.getMovies());
    }

    private sendRequest(verb: RequestMethod, url: string,
        data?: any): Observable<any> {
        return this.http.request(new Request({
            method: verb, 
            url: url, 
            body: data
        })).map(response => {
            return response.headers.get("Content-Length") != "0"
                ? response.json() : null;
        });
    }

    updateMovie(id: number, changes: Map<string, any>) {
        let patch = [];
        changes.forEach((value, key) =>
            patch.push({ op: "replace", path: key, value: value }));
        this.sendRequest(RequestMethod.Patch, moviesUrl + "/" + id, patch)
            .subscribe(response => this.getMovies());
    }

    movie: Movie;
    movies: Movie[];
    studios: Studio[] = [];

    get filter(): Filter {
        return this.filterObject;
    }

    deleteMovie(id: number) {
        this.sendRequest(RequestMethod.Delete, moviesUrl + "/" + id)
            .subscribe(response => this.getMovies());
    }
    deleteStudio(id: number) {
        this.sendRequest(RequestMethod.Delete, studiosUrl + "/" + id)
            .subscribe(response => {
                this.getMovies();
                this.getStudios();
            });
    }
}

【问题讨论】:

  • 您可能没有在post req 中传递数据,或者可能在get req 中传递空数据
  • 试试这个 -> this.http.request(new Request(verb.toString(),url,{ body: data }))。还要检查 http.request 方法的重载。您将在 client.d.ts 中找到它。问题在于您的动词是 RequestMethod 类型,但所需的输入是像这样的“GET”/“POST”。您将 httpclient 与 http RequestMethod 结合使用。因此,在您的 sendRequest 中,您需要引入一个选项来转换 RequestMethod.GET => "GET"。如果有帮助,请告诉我
  • 我很困惑。有没有办法做到这一点没有'RequestMethod?'。我只需要它工作,所以我不介意另一种不会很快被弃用的方法。
  • 是的,当然。 @Vancho 提到了你可以有 2 个方法 Get 和 Post 的方法,而不是调用 http.request,你可以直接调用 http.get 或 http.post。 (其中 => http : HttpClient)

标签: angular typescript


【解决方案1】:

下面应该工作:

private sendRequest(verb: RequestMethod, url: string,
    data?: any): Observable<Request> {
    return this.http.request(new Request({
        method: verb, 
        url: url, 
        body: data
    })).map(response => {
        return response.headers.get("Content-Length") != "0"
            ? response.json() : null;
    });
}

【讨论】:

  • 将 'any' 更改为 'Request' 后错误仍然存​​在 :(
  • 是的,这不会有帮助,因为您传递的请求参数是 HTTPRequest 类型(如果您在 client.d.ts 中看到),这将强制需要更多参数,如标头、凭据等。 .所以最好使用不同的http.request重载,请查看我上面的评论
【解决方案2】:

像这样在“@angular/http”中使用“Http”(不推荐使用这种方式)

从'@angular/http'导入{RequestMethod, Http, Request, Response};

不从 '@angular/common/http' 导入 { HttpClient };

将构造函数更改为:

constructor(private http: Http) {
    //this.filter.category = "drama";
    this.filter.related = true;
    this.getMovies(true);
}

来源:Angular.io -> api -> http -> Request

或未弃用您可以这样做:

...构造函数(私有http:HttpClient)...

  public get<T>(url: string, headers: object) {
    return this.http.get<T>(url, headers);
  }


  public post<T>(url: string, body: any, headers: object) {
    return this.http.post<T>(url, body, headers);
  }

【讨论】:

  • 我试图避免使用已弃用的方法。我之前也有过这样的工作,但我试图保持最新状态。
  • 获取请求:私有 sendRequest(verb: RequestMethod, url: string, data?: any): Observable { return this.http.get(url, { }); }
【解决方案3】:

有两种方法可以解决这个问题,或者像上面 Vancho else 提到的那样使用特定于它的 get 和 post 方法,让你开始尝试下面的代码:

private sendRequest(verb: RequestMethod, url: string,
    data?: any): Observable<any> {

    let method: string;

    switch (verb) {
        case RequestMethod.Get:
            method = "GET";
            break;
        case RequestMethod.Post:
            method = "POST";
            break;
    }

    return this.http.request(method, url, { body: data }).map(response => {
        return response.headers.get("Content-Length") != "0"
            ? response.json() : null;
    });
}

我不建议你走这条路线,因为它不可扩展,你应该有特定于 get/post/delet 方法的代码,所以你可以有 2-3 个方法:

sendGetRequest 和 sendPostRequest 分别有 http.get 和 http.post。

【讨论】:

    猜你喜欢
    • 2020-03-19
    • 2019-09-06
    • 2021-12-05
    • 2018-03-19
    • 2019-11-02
    • 2020-12-17
    • 1970-01-01
    • 2019-01-09
    • 2019-10-26
    相关资源
    最近更新 更多