如何使用角度5发布帖子请求
发布时间:2020-12-17 17:06:44 所属栏目:安全 来源:网络整理
导读:我想使用angular 5进行post resquest,但它给了我一个错误:这是代码: service.ts import { Injectable } from '@angular/core';import { Response,Headers } from '@angular/http';import { HttpClient,HttpErrorResponse } from '@angular/common/http';im
我想使用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)); } 它给了我一个错误:
解决方法
尝试在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")}) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |