【问题标题】:Type 'URLSearchParams' is not assignable to type 'URLSearchParams'类型“URLSearchParams”不可分配给类型“URLSearchParams”
【发布时间】:2017-09-01 13:09:19
【问题描述】:

我想向我的 webapi 发送一个带有一些搜索参数的 http.get 请求以获取学生列表。我找到了一些关于如何执行此操作的示例,但是在完全按照示例执行之后,我得到了这个奇怪的错误:

Type 'URLSearchParams' is not assignable to type 'URLSearchParams'. Two different types with this name exist, but they are unrelated.
Property 'rawParams' is missing in type 'URLSearchParams'.

这是我的组件:

import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map'
import { User } from '../_models/user';

@Injectable()
export class UserService {

options = new RequestOptions({ 'headers': new Headers({ 'Content-Type': 'application/json' })});

constructor(private http: Http) {
}

createAccount(newUser: User){
return this.http.post('http://localhost:64792/api/students', JSON.stringify(newUser), this.options)
.map((response: Response) => {              
    if(response.ok){
        console.log("Registration was a success");
        return true;
     } else {
         console.log("Registration failed");
         return false;
      }
 });
}

searchStudents(searchWords: Array<string>){
// Parameters obj-
 let params: URLSearchParams = new URLSearchParams();
 for(let i = 0; i < searchWords.length; i++){
 params.append('searchWords', searchWords[i]);
 }
 this.options.search = params;
 //Http request-
}
} 

什么可能导致这个错误?

【问题讨论】:

标签: angular typescript http get


【解决方案1】:

似乎本机 URLSearchParams 已声明为您当前的代码,而 new URLSearchParams(); 返回 angular.io 的 URLSearchParams object

导入'rxjs/add/operator/map',它应该可以工作。

import { URLSearchParams } from '@angular/http';

【讨论】:

    【解决方案2】:

    尝试使用set方法

    searchStudents(searchWords: Array<string>){
    // Parameters obj-
     let params: URLSearchParams = new URLSearchParams();
     for(let i = 0; i < searchWords.length; i++){
     params.set('searchWords', searchWords[i]);
     }
     this.options.search = params;
     //Http request-
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-02
      • 2019-06-02
      • 2018-01-04
      • 2020-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-26
      相关资源
      最近更新 更多