0
votes

This is an old angular code, I'm getting error with the Http, Headers, RequestOptions.

can someone help me fix this and get same function. Thanks in advance.

i used "import { HttpClient, HttpHeaders, HttpRequest } from '@angular/common/http';"

but some function are still not working properly here "let options = new HttpRequest({ headers: headers });"

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class PostProvider {
server: string = "http://localhost/server_api/"; // default


constructor(public http : Http) {

}

postData(body, file){
    let type = "application/json; charset=UTF-8";
    let headers = new Headers({ 'Content-Type': type });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.server + file, JSON.stringify(body), options)
    .map(res => res.json());
}
}
1
Can you please include the error in your question so that we know what is it exactly?navdbaloch

1 Answers

0
votes

Below Should Work Note the below Changes

  • changed import {Http} from '@angular/http' to import {HttpClient} from '@angular/common/http'
  • Removed JSON.stringify as it is not neccessary here
  • Removed The mapping map(res => res.json()) as by default angular returns an Object. I have added typecasting <any> to return an any type observable. You can change this
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class PostProvider {
server = "http://localhost/server_api/"; 

constructor(public http : HttpClient) { }

postData(body, file) {
  const headers = new HttpHeaders({
    'Content-Type':"application/json; charset=UTF-8"
  })

  return this.http.post<any>(this.server + file, body, {headers})
}