I'm unable to change the headers when doing a post request with http module in Angular (with Ionic).
Here is my code:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
const apiUrl = "https://webhook.site/c2d56330-84d4-47cf-9f98-472f7eac8000";
#Injectable({
providedIn: 'root'
})
export class APIService {
constructor(private http: HttpClient) { }
getToken(){
var body = {
'data1': 'data2',
'somedata3': 'data4',
};
let headers = new HttpHeaders().append('Content-Type', 'application/json');
this.http.post(apiUrl, JSON.stringify(body), {headers}).subscribe(data =>
console.log(data));
console.log(headers.get('Content-Type')); //return 'application/json'
}
}
Everything works well, but it still sends header "content-type: text/plain" instead of "content-type: application/json".
Do I type something wrong?
I'd prefer something like:
import { HttpHeaders } from '#angular/common/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
this.http.post<Foo>(this.apiUrl, body, httpOptions)
Also I don't see a need to stringify the body, just pass it as a "normal" object
Related
I have a little issue from an Angular app to get a code from my own server.
I´ve built up a little Spotify App for learning more about Angular 10 and have a little backend that I only use for get the Bearer code to call the Spotify API, but the fact is that in my Angular front I can´t save the code.
Tis is my service call code to the back:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { map } from 'rxjs/operators';
import { environment } from '../../environments/environment';
#Injectable({
providedIn: 'root'
})
export class SpotifyService {
token: any;
constructor(private http: HttpClient) {
console.log('Spotify service ready');
this.getAccesToken().subscribe(data => this.token = data['access_token']);
}
getAccesToken(){
return this.http.get(environment.server + `${environment.client_id}/${environment.client_secret}`)
.pipe(
map(res => res)
);
}
getQuery(query: any){
const headers = new HttpHeaders({
'Authorization': `Bearer ${this.token}`
});
const url = `https://api.spotify.com/v1/${query}`;
return this.http.get(url, {headers});
}
I´ve checked the recibed data and I get the request perfectly, but can´t save the data of the suscriber into a variable.
Thanks in advance!
Assuming your component code looks like below, you can make some adjustments and try it.
export class SomeComponent implements OnInit {
spotifyData;
user;
token;
constructor(private spotifyService: SpotifyService, private http: HttpClient) { }
ngOnInit() {
this.user = JSON.parse(localStorage.getItem('user'));
console.log(this.user);
this.token = this.user.token;
this.getSpotifyData();
}
getSpotifyData() {
this.spotifyService.getQuery(this.user, { headers: new HttpHeaders().set('Authorization', 'Bearer ' + this.token) }).subscribe(res => {
console.log(res);
if (res) {
spotifyData = res;
} else {
spotifyData = []
}
});
}
I'm using plain javascript to fetch data from php scripts server-side but I'd like to try it out using angular.
This code fetches a php file that in turn queries a database (simple select with filter, etc) and returns a json file to be used by the script and then displayed.
Is there a simple way of doing this with angular?
This is the script as it is now
fetch('service/select.php')
.then(function(response) {
return response.json();
})
.then(function(data) {
//do something with the data
});
and this is the php file it fetches:
<?php
require_once("config.php");
mysqli_set_charset($con, 'utf8mb4');
mysqli_query($con, "SET NAMES 'utf8mb4'");
$rs = mysqli_query($con, "select * from names");
while($row = mysqli_fetch_assoc($rs)) {
$res[] = $row;
}
echo json_encode($res, JSON_UNESCAPED_UNICODE);
?>
(I know the php file is vulnerable to sql injection, its just an example file to quickly query data, not used in production)
Demo HTTPClient module is your need
import {Injectable} from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
#Injectable()
export class DataService{
constructor(private http:HttpClient){ }
Post(url:string,body:any): Observable<any>{
return this.http.post<any>(url, body, httpOptions).pipe( retry(1), catchError(this.handleError) );
}
Get(url:string): Observable<any>{
return this.http .get<any>(url, httpOptions).pipe( retry(1), catchError(this.handleError) );
}
private handleError(error: any){
let body = error.json();
return body || {};
}
}
Angular provides HttpClient API to do HTTP requests. The response type of this API is Observable type of RxJS which has lots of built-in methods to
process your data.
You can do your HTTP request code as following in the angular way instead of fetch API.
const url = 'service/select.php';
const hdrs = new HttpHeaders({ 'Accept': accept ? accept : 'application/json; charset=utf-8' });
this.http.get(url, { headers: hdrs, observe: 'body', responseType: 'json'})
.subscribe(
data => // do whatever you want to do your data
err => // get the error response here
);
I am working on a sample Angular2 application which uses Spotify API to get data. When I run the code, I'm getting response Error in console as "Invalid Access Token". I have provided the correct access token, still the error persists, I'm not getting how to resolve it and what's wrong I'm doing.
import { Injectable } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class SpotifyService {
private searchUrl: string;
constructor(private _http: Http) { }
searchMusic(str: string, type = 'artist') {
const access_token = '<My Access Token Here>';
const headers = new Headers({ 'Authorization': 'Bearer ' + access_token });
this.searchUrl = 'https://api.spotify.com/v1/search?query='+str+'&offset=0&limit=20&type='+type+'&market=US';
return this._http
.get(this.searchUrl, { headers })
.map(res => res.json());
}
}
Error Screenshot :
You can check by adding one of the content-type in headers
var headers: Headers = new Headers({'Authorization': 'Bearer ' + access_token, 'Content-Type': 'application/x-www-form-urlencoded' });
OR
var headers: Headers = new Headers({'Authorization': 'Bearer ' + access_token, 'Content-Type': 'application/json' });
were you able to get a valid response by giving your access token in their api console?
https://developer.spotify.com/web-api/console/get-search-item/?q=tania+bowra&type=artist
service.ts
This is my service class. I want to request for a token from an API and display it in my console window. Where am I going wrong, the token is not being displayed. May some please help. Thanks
Apart from the token I will want to retrieve some JSON data but first I want to sort out the token.
import {Injectable } from '#angular/core';
import { Http, Response, Headers, RequestOptions} from '#angular/http';
import {Observable} from 'rxjs/Rx';
#Injectable()
export class StartPage{
constructor(public http: Http){}
credential() {
const url = 'https://xxx';
const body = {
"client_id": 'xxx',
"client_secret": 'xxx',
"grant_type": "client_credentials",
"scope": "transportapi:all"
};
let formData: FormData = new FormData();
for (let key in body) {
formData.append(key, body[key]);
}
const headers = new Headers(
{
'Accept': 'application/json'
});
return this.http.post(url, formData, {headers: headers});
}
}
app.component
This is my component class. I want to get a token from an API but the token is not being displayed.
import {Component} from '#angular/core';
import { Http, Headers } from '#angular/http';
import {Observable} from 'rxjs/Rx';
import {StartPage} from '../app/service';
#Component({
selector: 'my-app',
template: '<h1>Hello results {{results.access_token}}</h1>'
,
providers: [StartPage]
})
export class AppComponent{
results:String;
public testing:{};
constructor(public service: StartPage){
}
onSubmit(){
this.service.credential().subscribe(
res => {
this.results = res['access_token'];
console.log(this.results)
}
);
}
}
You are declaring 'results:String', so when you set an object (res['access_token']) is been saved as string....
Try declaring results as any ('results:any')
I have a json that is not being update on the first time I click on the button that updates it. The button in question calls this function:
recusaProposta(){
this.propostaService.atualizaDisputa(this.disputa)
.subscribe(
res => this.disputa.propostas_realizadas++,
error => console.log(error)
);
}
Now, at the first time I click on it nothing happens on the json but if I click on it again it does update the field I want (disputa.propostas_realizadas)
Here's the service:
import {Injectable} from '#angular/core';
import {Http, Headers, Response, RequestOptions} from '#angular/http';
import {Component} from '#angular/core';
import {Observable} from 'rxjs/Rx';
import {DisputaPropostaComponent} from './disputas-proposta.component';
import 'rxjs/add/operator/map';
#Injectable()
export class DisputaPropostaService{
contato:Object[] = [];
name: string;
headers:Headers;
url: string = 'http://localhost:3004/disputa';
constructor(private http: Http){}
atualizaDisputa (body:any): Observable<DisputaPropostaComponent[]>{
let bodyString = JSON.stringify(body); // Stringify payload
let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
let options = new RequestOptions({ headers: headers }); // Create a request option
return this.http.put(`${this.url}/${body['id']}`, body, options) // ...using post request
.map((res:Response) => res.json()) // ...and calling .json() on the response to return data
.catch((error:any) => Observable.throw(error.json().error || 'Ocorreu um erro em nosso servidor, tente novamente mais tarde')); //...errors if any
}
}
Can you guys help me? Thanks in advance.
The reason is that in your function you return disputa.propostas_realizadas before increasing it by 1. Replace your function with the code below and it should work.
recusaProposta(){
this.propostaService.atualizaDisputa(this.disputa)
.subscribe(
res => ++this.disputa.propostas_realizadas,
error => console.log(error)
);
}