我想使用angular 5进行post resquest,但它给了我一个错误:这是代码:
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
heroes :[]; createUser() { this.dataService.addUser(this.user2) .subscribe(hero => this.heroes.push(hero)); }
它给了我一个错误:
TypeError: this.selector is not a function
Stack trace:
CatchSubscriber.prototype.error@webpack-internal:///../../../../rxjs/_esm5/operators/catchError.js:108:26
解决方法
尝试在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帖子.并映射您的回复.
在ts文件中
createUser(){ this.dataService.addUser(this.user2).subscribe(data => {alert("Succesfully Added Product details")},Error => {alert("failed while adding product details")}) }