I Have a problem with the variable this in angularjs2 and ionic 2
I have this fuction:
getAnuncio(id_anuncio){
console.log(id_anuncio)
var token=this.local.get('token')._result;
var headers= new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Authorization', 'Token '+token);
datos="id_anuncio="+id_anuncio;
this.http.post('http://127.0.0.1:8000/envios/getAnuncioPorId/',datos , {
headers: headers
})
.subscribe(success => {
this.anuncio=success.json();
console.log("BIENNN");
console.log(success);
console.log(this.anuncio);
return this.anuncio;
}
}
I call it from another function:
cargarMapa(){
this.anuncio=this.getAnuncio(this.envio.anuncio);
console.log(this.anuncio);
//console.log(anuncio);
//this.getOferta(this.envio.oferta);
//console.log(this.oferta)
}
But when I try to log this.anuncio, it is undefined.
I need to store the data in a variable to use it from other function.
Anybody could help me?
Here is the code: https://github.com/p02diada/cyclaClientv2/blob/master/app/pages/sending-details/sending-details.js
You could leverage the do operator this way for this:
getAnuncio(id_anuncio){
console.log(id_anuncio)
var token=this.local.get('token')._result;
var headers= new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Authorization', 'Token '+token);
datos="id_anuncio="+id_anuncio;
this.http.post('http://127.0.0.1:8000/envios/getAnuncioPorId/',datos , {
headers: headers
})
.map(res => success.json())
.do(data => {
this.anuncio = data;
});
}
This way you can subscribe on the observable outside the getAnuncio method:
this.anuncio=this.getAnuncio(this.envio.anuncio).subscribe(
(anuncio) => {
// do something
console.log(anuncio);
}
);
Don't forget that things are asynchronous.
If you want to implement a kind of cache, use the following:
getAnuncio(id_anuncio){
if (this.anuncio) {
return Observable.of(this.anuncio);
} else {
var token=this.local.get('token')._result;
var headers= new Headers();
(...)
}
}
By using the this.anuncio directly is that you can't be sure that the data are there...
Related
i need to send a GET request from my JavaScript function to my python flask app. However, i tried to type the URL with the parameters manually and it worked. But i can't send the same request in a JS function. Response type is HTML.
This is how the URL should look like:
http://127.0.0.1:5000/books?rank=2&topic=Self improvement
I tried this, but it didn't work:
function sendRequest() {
const xhr = new XMLHttpRequest();
xhr.open('GET', '/books', {
rank: rank,
topic: topic
});
xhr.onload = function() {
console.log(xhr.response);
}
xhr.send();
}
What the URL looked like with this try:
http://127.0.0.1:5000/books
Please help!
You're trying to pass the parameters in a POST body (the third argument to open). That won't work for a GET, they have to be in the URL.
The easiest and least error-prone way is to use URLSearchParams (thank you Christopher for pointing that out when I forgot!):
const url = "/books?" + new URLSearchParams({rank, title});
Live Example:
const rank = 42;
const title = "Life, the Universe, and Everything";
const url = "/books?" + new URLSearchParams({rank, title});
console.log(url);
These days, you'd usually use the more modern fetch rather than XMLHttpRequest:
function sendRequest() {
const url = "/books?" + new URLSearchParams({rank, title});
fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
return response.text(); // Or `.json()` or one of the others
})
.then((data) => {
console.log(data);
})
.catch((error) => {
// ...handle/report error...
});
}
But if you prefer to use XMLHttpRequest, put the parameters in the URL (and handle errors):
function sendRequest() {
const xhr = new XMLHttpRequest();
const url = "/books?" + new URLSearchParams({rank, title});
xhr.open("GET", url);
xhr.onload = function () {
console.log(xhr.response);
};
xhr.onerror = function () {
// ...handle/report error...
};
xhr.send();
}
(You can also use string concatenation and encodeURIComponent to build the URL, but it's more work and more error-prone. :-) )
I made a code with fetch() based on the comments above, let me know if you get any errors. Hope this helps, XMLHttpRequest() is not used much due to its complexity.
async function sendRequest(){
const url = 'your URL';
await fetch(url,{
method: "GET",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
}).then(response=>{
if(response.status !=200) {
throw new Error(`HTTP ERROR:${response.status}`);
}
return response.text()
}
).then(data => {
console.log(data);
// convert to html
}).catch(err => {
console.log(err);
})
}
I have a problem with HttpParams and HttpHeaders after migrating my project from Angular 7 to Angular 8. When I call the API the params are not added. If anyone can help me fix this problem it will be great.
Here is the method in which I define the headers as well as the params.
fetchJson(url: string, parameters ? : any) {
this.token = this.cookieService.get('access_token');
this.contrat_token = this.cookieService.get('contrat_token');
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');
headers = headers.append('Authorization', 'Bearer ' + this.token);
headers = headers.append('contrat_token', this.contrat_token);
let params = new HttpParams()
params.set('search', parameters);
console.log('les headers');
console.log(headers);
console.log('params');
console.log(params.toString())
return this._http.get(url, {
headers,
params
}).pipe(map((resp: any) => {
if (resp.status === 401 || resp.status == 401 || resp.status.toString() == "401") {
this.clearCookie();
} else {
let reponse = resp;
if (reponse == -1 || reponse == "-1") {
this.router.navigate(["/"]);
}
}
return resp;
}
And I call this method in my services as follows.
getDetailThematiquePrevNext(id: string, typeBase: string) {
let URL = this.urlDecorator.urlAPIDecorate("DI", "GetDetailThematiqueHeaderPrevNext");
let params = this.urlDecorator.generateParameters({
id: id,
typeBase: typeBase,
});
return this.apiFetcher.fetchJson(URL, params);
}
Reason provided by Cue is correct, You need to use chaining or do what you did for headers
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');
headers = headers.append('Authorization', 'Bearer ' + this.token);
headers = headers.append('contrat_token', this.contrat_token);
let params = new HttpParams()
params = params = params.set('search', parameters);
More readable way to write this would be as follows
const headers = new HttpHeaders()
.append('Content-Type', 'application/json')
.append('Authorization', 'Bearer ' + this.token)
.append('contrat_token', this.contrat_token);
const params = new HttpParams().set('search', parameters);
Also, you can drop Content-Type header, as it is json by default
Probably due to lazy parsing. You have to do a get or getAll to access values to determine the state.
HttpParams class represents serialized parameters, per the MIME type application/x-www-form-urlencoded. The class is immutable and all mutation operations return a new instance.
HttpHeaders class represents the header configuration options for an HTTP request. Instances should be assumed immutable with lazy parsing.
You may want to pass your options directly into the instance for both headers and params:
let headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.token,
'contrat_token': this.contrat_token
});
let params = new HttpParams({
search: parameters
});
As #Siraj stated in an answer, there are alternative ways to set values for headers and params such as set...
let headers = new HttpHeaders().set('name', 'value');
let params = new HttpParams().set('name', 'value');
Or append...
let headers = new HttpHeaders().append('name', 'value');
let params = new HttpParams().append('name', 'value');
The important thing to note here is that these methods require chaining otherwise each method creates a new instance.
You could also convert objects like so:
let headerOptions = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.token,
'contrat_token': this.contrat_token
}
let headers = new HttpHeaders();
Object.keys(headerOptions).forEach((key) => {
headers = headers.set(key, headerOptions[key]);
});
It's also worth avoiding any binding of objects by reference, and instead pass as parameters:
return this._http.get(url, {
headers: headers,
params: params
});
And finally, because your type annotation is "any" for the parameters argument, params expects HttpParamsOptions which is a key/value object where values must be a string annotation.
let params = new HttpParams({
search: JSON.stringify(parameters)
});
Try console.log(params.getAll('search')) but, to make sure headers and params are sent, a better place to check will be Network tab in DevTools.
I want use my api to send e-mail in some cases,the service (infobip) docs show an example in JS but it don't work in my api with nodejs and expressjs. Can someone help me?
/*----Sending fully featured email----*/
function createFormData(data) {
var formData = new FormData();
for (var key in data) {
formData.append(key, data[key]);
}
return formData;
}
//Dummy File Object
var file = new File([""], "filename");
var data = {
'from': 'Sender Name <from#example.com>',
'to': 'recipient1#example.com',
'subject': 'Test Subject',
'html': '<h1>Html body</h1><p>Rich HTML message body.</p>',
'text': 'Sample Email Body',
'attachment': file,
'intermediateReport': 'true',
'notifyUrl': 'https://www.example.com/email/advanced'
};
var xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.addEventListener('readystatechange', function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open('POST', 'https://{base_url}.infobip.com/email/1/send', false);
xhr.setRequestHeader('authorization', 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==');
xhr.setRequestHeader('accept', 'application/json');
xhr.send(createFormData(data));
You should use https from nodejs.
Here an example code to getting started. For infopib it seems to be so normal Post request.
I tried to create an account on this page, but registration seems to can be completed only over sales. So I couldn't provide a working example...
This is why I can only provide a general example how to make an https POST call, which should be a good starting point to develop your solution:
const https = require('https')
const data = JSON.stringify({
todo: 'Buy the milk'
})
const options = {
hostname: 'yourURL.com',
port: 443,
path: '/todos',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
}
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', (d) => {
process.stdout.write(d)
})
})
req.on('error', (error) => {
console.error(error)
})
req.write(data)
req.end()
I want to set token in authorization header but the token is set null. I tried to get the token from chrome storage but token is not set though i get the token from the storage when i console the result['user_token'] inside the callback.
here is the code
var token = null; // i need this token in fetchTopics as well
function fetchCurrentUser() {
const apiUrl = `api2.navihq.com/get_current_user`;
chrome.storage.sync.get(['user_token'], function(result) {
token = result['user_token'];
});
console.log('token', token); // getting null
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', `Token: ${token}`)
fetch(apiUrl, {
method: 'GET',
headers
})
.then(function(response) {
console.log('response', response);
return response.json()
})
.then(function(data) {
console.log('data', data);
return JSON.parse(atob(data.user))
})
}
$(window).bind('load', function() {
document.addEventListener('click', init);
fetchCurrentUser();
fetchTopics();
});
How do i now set the token in authorization header?
The sync in chrome.storage.sync.get doesn't mean it's synchronous
the fact it takes a callback shows it is Asynchronous - not that taking a callback guarantees something is asynchronous of course, but in this case it's clear that it is
So put the fetch inside the callback
function fetchCurrentUser() {
const apiUrl = `api2.navihq.com/get_current_user`;
chrome.storage.sync.get(['user_token'], function(result) {
var token = result['user_token'];
console.log('token', token); // getting null
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', `Token: ${token}`)
fetch(apiUrl, {
method: 'GET',
headers
}).then(function(response) {
console.log('response', response);
return response.json()
}).then(function(data) {
console.log('data', data);
return JSON.parse(atob(data.user))
})
});
}
Alternatively you can "promisify" the chrome.storage.sync.get function
function fetchCurrentUser() {
const chromeStorageGetPromise = key =>
new Promise(resolve => chrome.storage.sync.get(key, resolve));
const apiUrl = `api2.navihq.com/get_current_user`;
chromeStorageGetPromise(['user_token'])
.then(({user_token: token}) => {
console.log('token', token);
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', `Token: ${token}`);
return fetch(apiUrl, {
method: 'GET',
headers
});
}).then(response => {
console.log('response', response);
return response.json();
}).then(data => {
console.log('data', data);
return JSON.parse(atob(data.user));
})
}
I am currently trying to call a jersey REST API that I have running locally on localhost:8080 through Angular 4 using HttpClient.
My Code:
```
ngOnInit() {
const headers = new HttpHeaders();
headers.append('Authorization', 'Basic ' + btoa('username:password'));
headers.append('Content-Type', 'application/json');
this.http.get('http://localhost:8080/mycall?myparam=myvalue', {headers: headers}).subscribe(data => {
console.log(data);
});
}
```
When I make this call I get a 401 error saying that I am Unauthorized. However, when I run this through postman it goes through just fine. What am I doing wrong here?
NOTE: this is not a CORS issue, I am currently allowing CORS through an extension on firefox
HttpHeaders are immutable, so you need to do something like that
ngOnInit() {
const headers = new HttpHeaders()
.append('Authorization', 'Basic ' + btoa('username:password'))
.append('Content-Type', 'application/json');
this.http.get('http://localhost:8080/mycall?myparam=myvalue', {headers: headers}).subscribe(data => {
console.log(data);
});
}
Actually you should not need the Content-type here for a GET request
I think the issue is that you haven't passed in your custom request headers to HttpClient, which is causing the unauthorised error.
Please try something like this.
const headers = new HttpHeaders();
headers.append('Authorization', 'Basic ' + btoa('username:password'));
headers.append('Content-Type', 'application/json');
const options = new RequestOptions({headers: headers});
this.http.get('http://localhost:8080/mycall?myparam=myvalue', options ).subscribe(data => {
console.log(data);
});
You can simply pass in your RequestOptions to http.get as it does accept headers as an optional parameter. Please check following link for more details on the usage.
https://angular.io/api/common/http/HttpClient#get
Also, remember to import RequestOptions as well.