如何用Angular 5发出发布请求
问题描述:
我想使用角度5进行发布请求,但这给了我一个错误:这是代码:
i want to make a post resquest using angular 5, but it gives me an error : here is the code :
service.ts
service.ts
import { Injectable } from '@angular/core';
import { Response, Headers } from '@angular/http';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import { catchError, retry } from 'rxjs/operators';
//Grab everything with import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';
import { Observer } from 'rxjs/Observer';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { User } from '../iterface';
import { HttpHeaders } from '@angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
};
@Injectable()
export class DataService {
_baseUrl: string = '';
constructor(private http: HttpClient) {
this._baseUrl = "http://sso-app-bonita.qualif.dauphine.fr:8080/bonita/";
}
addUser(user: User): Observable<User> {
return this.http.post<User>(this._baseUrl, '/API/identity/user', httpOptions)
.pipe(
catchError(this.handleError('addHero', user))
);
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an ErrorObservable with a user-facing error message
return new ErrorObservable(
'Something bad happened; please try again later.');
};
}
component.ts
component.ts
heroes :[];
createUser() {
this.dataService.addUser(this.user2)
.subscribe(hero => this.heroes.push(hero));
}
它给我一个错误:
TypeError:this.selector不是一个函数 堆栈跟踪: CatchSubscriber.prototype.error@webpack-internal:///../../../../rxjs/_esm5/operators/catchError.js:108:26
TypeError: this.selector is not a function Stack trace: CatchSubscriber.prototype.error@webpack-internal:///../../../../rxjs/_esm5/operators/catchError.js:108:26
答
尝试在您的service.ts中使用它
try using this in your service.ts
import {Headers} from 'angular2/http';
var headers = new Headers();
headers.append(headerName, value);
addUser(user : User){
return this.http.post(this._baseUrl + '/API/identity/user',user,{ headers: headers}).map((response: Response) =>{
console.log (response.json());
})
}
在这里,您需要将用户界面发送到HTTP post.并绘制您的回应.
here you need to send user interface to HTTP post. and map your response.
在ts文件中
createUser(){
this.dataService.addUser(this.user2).subscribe(data => {alert("Succesfully Added Product details")},Error => {alert("failed while adding product details")})
}