Angular 2 is removing JSON curly braces on HTTP POST response - json

Hello I have an issue where I am making a POST request to an API in Angular 2 and when I make the HTTP call, the Angular 2 returns a response, but instead of the expected JSON response, it returns a response in plain text with all the curly braces removed.
Example:
instead of {"type" : "string"} I get "typestring".
Here is my code:
let headers = new Headers({ 'content-type': 'application/json' });
let options = new RequestOptions({headers: headers});
this.http.post('api url', body, options).subscribe(data => console.log(data));
I understand there is a data.json() function but when I try that it just gives a
Unexpected token N in JSON at position 0 error.
Any help is appreciated, thanks.

try this
service.ts
import { Observable } from 'rxjs/Rx';
#Injectable()
export class MyService {
createRecored(body: any): Observable<any> {
let headers = new Headers({ 'content-type': 'application/json' });
let options = new RequestOptions({headers: headers});
this.http.post('api url', body, options)
.map(res => res.json())
.catch(error => Observable.throw(error));
}
}
component.ts
export class MyComponent {
constructor(private myService: MyService ) {}
doPost() {
this.myService.createRecored(body)
.subscribe(data => {
console.log('data', data);
}
}
}

Related

TypeError: errorResponse.json is not a function - Tried to remove holding response as Json but still facing issue [duplicate]

I am having an issue with my API Service. This service connects to my nodejs backend api.
The error says
ERROR TypeError: res.json is not a function
I am getting this error after recently updated this service to use the HTTPClient instead of Http. Im getting this reponse because im missing the old http with the new? if thats the case is there an new Response and how do i use it?
import { Injectable } from '#angular/core';
import { environment } from '../../environments/environment';
import { HttpHeaders, HttpClient, HttpParams } from '#angular/common/http';
import { Response } from '#angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { JwtService } from './jwt.service';
#Injectable()
export class ApiService {
constructor(
private http: HttpClient,
private jwtService: JwtService
) {}
private setHeaders(): HttpHeaders {
const headersConfig = {
'Content-Type': 'application/json',
'Accept': 'application/json'
};
if (this.jwtService.getToken()) {
headersConfig['Authorization'] = this.jwtService.getToken();
}
return new HttpHeaders(headersConfig);
}
private formatErrors(error: any) {
return Observable.throw(error.json());
}
get(path: string, httpParams: HttpParams = new HttpParams()): Observable<any> {
return this.http.get(`${environment.api_url}${path}`, { headers: this.setHeaders(), params: httpParams })
.catch(this.formatErrors)
.map((res: Response) => res.json());
}
put(path: string, body: Object = {}): Observable<any> {
return this.http.put(
`${environment.api_url}${path}`,
JSON.stringify(body),
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res: Response) => res.json());
}
post(path: string, body: Object = {}): Observable<any> {
return this.http.post(
`${environment.api_url}${path}`,
body,
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res: Response) => res.json());
}
delete(path): Observable<any> {
return this.http.delete(
`${environment.api_url}${path}`,
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res: Response) => res.json());
}
}
HttpClient.get() applies res.json() automatically and returns Observable<HttpResponse<string>>. You no longer need to call this function yourself.
See Difference between HTTP and HTTPClient in angular 4?
You can remove the entire line below:
.map((res: Response) => res.json());
No need to use the map method at all.
Don't need to use this method:
.map((res: Response) => res.json() );
Just use this simple method instead of the previous method. hopefully you'll get your result:
.map(res => res );
Had a similar problem where we wanted to update from deprecated Http module to HttpClient in Angular 7.
But the application is large and need to change res.json() in a lot of places.
So I did this to have the new module with back support.
return this.http.get(this.BASE_URL + url)
.toPromise()
.then(data=>{
let res = {'results': JSON.stringify(data),
'json': ()=>{return data;}
};
return res;
})
.catch(error => {
return Promise.reject(error);
});
Adding a dummy "json" named function from the central place so that all other services can still execute successfully before updating them to accommodate a new way of response handling i.e. without "json" function.

HTTP call - req.url is undefined

I want to get data from an API link. Api Link and API-key are correct. When I try it with POSTMAN it returns result. When I run the app with http call it gives this error:
"Uncaught (in promise): TypeError: req.url is undefined
HttpXsrfInterceptor.prototype.intercept...
What is the problem can someone please tell me?
Here is my code.
App module.ts
import { HttpClientModule, HttpClient } from '#angular/common/http';
#NgModule({
imports: [
HttpModule ]
})
home.ts
import { HttpHeaders, HttpClient } from '#angular/common/http';
export class A{
apiUrl = "yyy-yyy-yyy";
constructor(private http: HttpClient){
this.getData();
}
getData(){
let headers = { headers: new HttpHeaders({ 'Accept': 'application/json',
'user-key': 'xxx-xxx'})};
return this.http.get(this.apiUrl, headers).subscribe(res=>
console.log('RES: ', res));
}
}
Error screenshot;
enter image description here
Firstly you want to have a service like that:
service.ts
constructor(private http: Http
) { }
public mygetdata(): Observable<Data[]> {
let headers = new Headers();
headers.append('user-key': 'xxx-xxx');
return this.http.get(this.apiUrl), {
headers: headers
})
.map((response: Response) => {
let res = response.json();
if (res.StatusCode === 1) {
} else {
return res.StatusDescription.map(data=> {
return new Data(data);
});
}
})
}
Component.ts
public data : Data[];
getdata() {
this.service.mygetdata().subscribe(
data => {
this.data = data;
}
);
}

Angular 2 Service Not Returning JSON from HTTP Response

I'm attempting to return JSON data from a web api, the service collects this fine and when you output this to the console it works and returns what I expect, but when I try to return the data to somewhere outside the service I can only get back 'undefined' with no errors.
Service Method
// Dashboard API Services
getModules() {
this._http.request(this._baseUrl + "Modules/Get").subscribe((res: Response) => {
this.modules = res.json();
});
return this.modules;
}
Service Call (in component)
import { Component, OnInit } from '#angular/core';
import { KoapiService } from '../koapi.service';
import { Http } from "#angular/http";
#Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
modules: any;
constructor(private _koapi: KoapiService) { }
ngOnInit() {
this.modules = this._koapi.getModules();
console.log(this.modules);
}
}
Found a great article on much better way to do this here: https://hassantariqblog.wordpress.com/2016/12/03/angular2-http-simple-get-using-promises-in-angular-2-application/
Changed my code to the following, meaning the service can take any URL now from from the service call as opposed to inside the service:
Service Method(s):
// On successful API call
private extractData(res: Response) {
let body = res.json();
return body || {};
}
// On Erronious API Call
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
// Basic Get
getService(url: string): Promise<any> {
return this._http
.get(this._baseUrl + url)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
Service Call:
// Get Enabled Modules
this._koapi
.getService("Modules/Get")
.then((result) => {
this.modules = result;
console.log(this.modules);
})
.catch(error => console.log(error));
}
1.
const headers = new Headers({
'Content-Type': 'application/json',
'Cache-control': 'no-cache',
Expires: '0',
Pragma: 'no-cache'
});
const options = new RequestOptions({ headers: headers });
You have to send this 'options' along with url.

How to get HTTP JSON-response into HTML (Ionic2, Angular2, TypeScript, PHP, JSON)?

I am currently working on my first Ionic 2 app, but I am not yet very much into typescript..
I want to call the authenticate() method in my constructor and afterwards to
get the whole JSON response into the textarea
and/or
access the username and password value of the json response in my HTML
TypeScript:
export class WelcomePage {
public data: string;
username: string;
password: string;
constructor(public navCtrl: NavController, public http: Http) {
this.authenticate();
}
authenticate() {
var creds = { username: 'user1', password: 'pw1' };
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.http.post('http://www.xyz.api.php', creds, {
headers: headers
})
.map(res => res.json())
.subscribe(
data => this.data,
err => this.logError(err),
() => console.log('Completed')
);
}
}
Response I already got from API:
{ "Person":[ {"Username":"user1","Password":"pw1"} ] }
HTML:
<textarea>here: {{data}}</textarea>
--> textarea is empty
You would want to extract the object that is inside the array, which is inside Person:
.map(res => res.json().Person[0]) // extract object
Furthermore, you need to assign the data to this.data like so:
.subscribe(
data => this.data = data // here!
....
Then use (together with the safe navigation operator ? here.)
{{data?.Username}} and {{data?.Password}}

Angular2 Http post 400

I have this service:
#Injectable()
export class HttpserviceService {
baseUrl: string = "http://localhost:3000/";
headers = new Headers({
'accept': 'application/json'
});
post(url: string, data: any): Observable<any> {
//send post request
return this.http.post(this.baseUrl+url, JSON.stringify(data))
.map(this.extractData) //this works
.catch(this.handleError); //this as well
}
}
and when I subscribe to that method:
user: User = {
username: "test",
password: "12345"
}
authUrl: string = 'user/auth';
return this.http.post(this.authUrl, user)
.subscribe(data => {
//console.log(data);
});
I'm getting an
Status Code:400 Bad Request
What can be wrong?
When I request using postman everything works ok
In postman i see that you have 1 header. Which you are not sending in angular
Try following, headers should go as a third parameter
post(url: string, data: any): Observable<any> {
//send post request
return this.http.post(this.baseUrl+url, JSON.stringify(data), {headers: this.headers})
.map(this.extractData) //this works
.catch(this.handleError); //this as well
}