如何使用角度5发布帖子请求

时间:2018-02-02 09:45:47

标签: angular

我想使用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不是函数   堆栈跟踪:   CatchSubscriber.prototype.error@webpack-internal:///../../../../rxjs/_esm5/operators/catchError.js:108:26

5 个答案:

答案 0 :(得分:7)

尝试在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")})
}

答案 1 :(得分:7)

让我们试一试......

//FileName: login.service.ts
import { Injectable } from '@angular/core';
import { HttpParams, HttpClient, HttpHeaders } from '@angular/common/http';
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';

import { catchError, retry } from 'rxjs/operators';

@Injectable()
export class LoginService {
    private _loginUrl = 'http://1.2.3.4/signin'; //the api url where we need to make a call
    constructor(private _http: HttpClient) {} //this initialized the HttpClient which we use to do a post or get call

    //setting body of the parameters to send via post 
    private body = new HttpParams()
    .set('username', 'onetap')
    .set('password', '123456');

    checkLogin(){
         return this._http.post(this._loginUrl,
            this.body.toString(),
            {
              headers: new HttpHeaders()
                .set('Content-Type', 'application/x-www-form-urlencoded')
            }
          )
        .pipe(
        catchError(this.handleError) // then handle the error
       );
    }
  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 observable with a user-facing error message
    return throwError(
      'Something bad happened; please try again later.');
  }
}

让我现在解释一下...... 首先要做的是......去参考这个link,这是关于如何设置httpclient并使用它的实例的基本指南。

在此代码中,我们从导入开始:
可注入:一个装饰器,可以帮助您将此服务注入到您需要的任何组件中。只需导入然后在@Component提供程序中设置它然后在构造函数中创建它的实例并使用 this 来使用它。

HttpParams :设置要为'Content-Type'发送的参数或数据:'application / x-www-form-urlencoded'。

HttpClient :这是我们实现get,post put方法的模块。

throwError,catchError,retry :这可能是你研究的功课。

checkLogin()实现post方法。使用HttpParams我们创建了body实例并将其传递给checkLogin 发布请求将采用3个参数。 1. Url,2。要发送的数据或正文,3。可选标题。

现在我们从下面给出的组件onSubmit方法中调用这个checkLogin

    onSubmit() {
        this.loginService.checkLogin()
        .subscribe(resp => {
            this.user = {
                username: resp['username'],
                email: resp['email'],
                password: resp['password']
            };
            console.log(this.user);//Check if we are getting data from server
        });
                

    }

完成所有这些后。如果您遇到CORS问题,如果您在本地主机或其他服务器上,则可能会遇到此问题。使用以下代码

这是服务器端代码

DO

npm install cors --save

只需在请求所在的主文件中添加这些行。

const cors = require('cors');
const express = require('express');
let app = express();
app.use(cors());
app.options('*', cors());

答案 2 :(得分:3)

这真的很简单,按照我记下来的那样。

//导入标题

import { HttpClient, HttpHeaders } from '@angular/common/http';

//创建标题

const ParseHeaders = {
 headers: new HttpHeaders({
  'Content-Type'  : 'application/x-www-form-urlencoded'
 })
};

//创建帖子请求

let _URL = "www.example.com/postdata";
let FormData = "FormData1="+Data1+"&FormData2"+Data2
this.httpClient.post(_URL,FormData,ParseHeaders).subscribe((res) => {
 console.log(res);
});

在服务器端接收时, 如果它是PHP然后使用$ _POST ['FormData1']; 这确实有用。

答案 3 :(得分:2)

您缺少要发布的数据,例如: -

this.http.post("https://reqres.in/api/users/2'",
    {
      "name": "morpheus",
      "job": "leader"
    })
    .subscribe(
        (val) => {
            console.log("POST call successful value returned in body", 
                        val);
        },
        response => {
            console.log("POST call in error", response);
        },
        () => {
            console.log("The POST observable is now completed.");
        });
}

在您的情况下 this.http.post<User>(this._baseUrl+'/API/identity/user', <yourdata> httpOptions)

您也可以查看rxjs imports

import { catchError, map } from "rxjs/operators";

答案 4 :(得分:0)

首先创建一个组件服务:

ng g s <<name of component service>>

然后导入httpClient的标头:

import { HttpClient, HttpHeaders } from '@angular/common/http';

第二次进入.ts组件服务,将httpClient对象注入到构造函数中:

constructor(private http:HttpClient) { }

留在组件服务中并创建一个函数,它将您的信息纳入常规组件:

 public saveUser(data)
       {
        const httpOptions = {
          headers: new HttpHeaders({
            'Content-Type':  'application/json',
           // 'Authorization': this.jwt
          })
        };

        return this.http.post(this._baseUrl+'/API/identity/user',data,httpOptions);
       }

只需将其添加到普通组件中,就可以了:

 constructor(private user:NameofComponentService) { }
     this.user.saveUser(this.liste).subscribe(data=>{  
    //console.log(data);

  },err=>{
    console.log(err.error.message);
  })