簡體   English   中英

屬性“ requestOptions”在類型上不存在

[英]Property 'requestOptions' does not exist on type

我想將數據從Angular Web客戶端發送到WebAPI服務。在此post方法中,我收到了編譯錯誤。'[ts]屬性'requestOptions'在'UserService'類型上不存在(Current Typescrpipt)。

import { Injectable } from '@angular/core';
import { Http,Response } from '@angular/http';
import { Observable } from 'rxjs/Rx'; ///Allow clients to subscribbe responces asnc and add Rx when handling errors catch block
import {User} from './user';
import {HttpClientModule} from '@angular/common/http';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import 'rxjs/Rx';


@Injectable()
export class UserService {

  constructor( private http : Http) { 

  }


  RegisterUser(user :User) {

    const headerDict = {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Access-Control-Allow-Headers': 'Content-Type',
      }

      const requestOptions = {                                                                                                                                                                                 
        headers: new HttpHeaders(headerDict), 
      };

      const data = JSON.stringify(User);
      return this.http.post("http://localhost:53269/Api/RegisterUser", data, this.requestOptions );

      }



}

使用HttpClientModule及其HttpClient抽象。 另外,您不需要使用JSON.stringify這是額外的

@Injectable()
export class UserService {

   constructor(private httpClient: HttpClient) { }

   RegisterUser(user: User) {

      const headerDict = {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Access-Control-Allow-Headers': 'Content-Type',
      };

      const requestOptions = {                                                                                                                                                                                 
          headers: new HttpHeaders(headerDict), 
      };

      return this.httpClient.post("http://localhost:53269/Api/RegisterUser", user, requestOptions);   
  }    

}

一注。 與實際問題無關。 不要從rxjs/Rx導入任何內容。 這將使您的捆綁包變得巨大。 如果要導入Observable只需像導入

import { Observable } from 'rxjs/Observable'

如果您需要一些運算符,請與rxjs/operatorsrxjs/observables/分開導入

使用帶有HttpClient eihter HttpClientModule或帶有Http HttpModule現在已棄用

你可以試試這個

  const headersOption = new HttpHeaders().set('Content-Type': 'application/json',
    'Accept': 'application/json',
    'Access-Control-Allow-Headers': 'Content-Type')

  const data = JSON.stringify(User);
  return this.http.post("http://localhost:53269/Api/RegisterUser", data, {headers:headersOption});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM