I want to send data to WebAPI service from Angular web client .In this post method im getting an compile error .'[ts] Property 'requestOptions' does not exist on type '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 );
}
}
Use HttpClientModule
with its HttpClient
abstraction. Also you don't need to use JSON.stringify
- it is extra
@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);
}
}
One note. Not related to the actual issue. Don't import anything from rxjs/Rx
. This will make your bundle huge. If you want to import Observable
- just import like
import { Observable } from 'rxjs/Observable'
If you want some operator - import it separately from rxjs/operators
or rxjs/observables/
Use eihter HttpClientModule
with HttpClient
or HttpModule
with Http
- which is deprecated now
you can try this
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});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.