Ionic 2 Json parse - json

How can i parse json data
data = "{\"msg_ok\": \"Uye olusturuldu\", \"user_id\": 181, \"token\": \"8650bfe987a3d619445f3d4905e1ae863e4be85f\"}"
I want to use token data
I tried like this code but not working..
Thanx to now
var headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json' );
//headers.append('Authorization' , 'Basic '+ btoa(tok));
let options = new RequestOptions({ headers: headers });
let postParams = {
username: this.uyelik['username'],
email:this.uyelik['email'],
password:this.uyelik['password']
}
this.http.post("https://deneme.com/api/v1.0/users/", postParams, options)
.subscribe(data => {
console.log(data['_body']);
this.veri = data['_body'];
this.veri = JSON.parse(this.veri);
console.log(this.veri['token']);
}, error => {
console.log(error);// Error getting the data
});
I SOLVED PROBLEM ;
var headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json' );
//headers.append('Authorization' , 'Basic '+ btoa(tok));
let options = new RequestOptions({ headers: headers });
let postParams = {
username: this.uyelik['username'],
email:this.uyelik['email'],
password:this.uyelik['password']
}
this.http.post("https://iothook.com/api/v1.0/users/", postParams, options)
.subscribe(data => {
//console.log(data['_body']);
veri = data['_body'];
veri= veri.slice(1, -1);
veri = veri.replace(/\\/g, "");
veri = JSON.parse(veri);
console.log(veri.token);
}, error => {
console.log(error);// Error getting the data
});

Try This.
this.http.post("https://deneme.com/api/v1.0/users/", postParams, options)
.map((res: Response) => res.json())
.subscribe(data => {
console.log(data['_body']);
this.veri = data['_body'];
this.veri = JSON.parse(this.veri);
console.log(this.veri['token']);
}, error => {
console.log(error);// Error getting the data
});

Parse like this-
var a = '{\"msg_ok\": \"Uye olusturuldu\", \"user_id\": 181, \"token\": \"8650bfe987a3d619445f3d4905e1ae863e4be85f\"}';
a.replace(/\//g, "");
var token = JSON.parse(a).token;
console.log(token)

Related

Angular 6 - get csv response from httpClient

Can any one please give an example of fetching application/octet-stream response from angular 6 httpClient. I am using the below code and it doesn't work ( I get unknown error - 401 response) -
import { saveAs } from 'file-saver';
getJobOutput() {
this.workflowService.fetchOutput(this.jobId,this.outputId).subscribe((response : any) => { // download file
var blob = new Blob([response.blob()], {type: 'application/octet-stream'});
var filename = 'file.csv';
saveAs(blob, filename);
});
}
Service is as below -
fetchOutput(jobId : string, outputId) {
var jobOutputURL = "myEnpoint";
var params = this.createHttpAuthorization(jobOutputURL,"GET");
params["format"] = "csv";
const options = {
headers: new HttpHeaders( { 'Content-Type': 'application/octet-stream',
'Accept' : 'application/octet-stream',
'Access-Control-Allow-Origin' : '*'}
)};
var endpoint = `${jobOutputURL}?oauth_consumer_key=${params["oauth_consumer_key"]}&oauth_signature_method=${params["oauth_signature_method"]}&oauth_nonce=${params["oauth_nonce"]}&oauth_timestamp=${params["oauth_timestamp"]}&oauth_version=1.0&format=${params["format"]}&oauth_signature=${params["oauth_signature"]}`;
return this.httpClient.get(endpoint, {...options, responseType: 'blob'});
}
To fetch an application/octet-stream, you have to set arraybuffer as the response type in the Angular HttpHeaders.
This is the service method:
fetchOutput(): Observable<ArrayBuffer> {
let headers = new HttpHeaders();
const options: {
headers?: HttpHeaders;
observe?: 'body';
params?: HttpParams;
reportProgress?: boolean;
responseType: 'arraybuffer';
withCredentials?: boolean;
} = {
responseType: 'arraybuffer'
};
return this.httpClient
.get('https://your-service-url.com/api/v1/your-resource', options)
.pipe(
map((file: ArrayBuffer) => {
return file;
})
);
}
This is the call to the service method and to the saveAs function:
this.yourService
.fetchOutput()
.subscribe((data: any) => {
const blob = new Blob([data], { type: 'application/octet-stream' });
const fileName = 'Your File Name.csv';
saveAs(blob, fileName);
})
As other users are suggestion: 401 Unauthorized is usually a client side error due to missing credentials.

Post image/file (multipart) with Angular6

I try to post an image with http.post from Angular6.
See below my rest service and component.
Service
setOptions(data: boolean = false, headersToSet?: any): any {
let token: string;
const headers = [];
token = JSON.parse(localStorage.getItem('SOSF_MANAGER_TOKEN'));
// AUTHORIZATION
headers['Authorization'] = 'Bearer ' + token;
headers['Content-Type'] = data ? 'multipart/form-data' : 'application/json';
// OTHER HEADERS
if (headersToSet !== undefined) {
for (const headerName of Object.keys(headersToSet)) {
headers[headerName] = headersToSet[headerName];
}
}
return { headers };
}
// POST
postDb(url: string, body: any): Observable<any> {
let options: any;
options = this.setOptions(body instanceof FormData);
url = this.url + url;
if (!(body instanceof FormData)) {
body = JSON.stringify(body);
} else {
// TO DO
}
console.log(body);
if (environment.console_log_construct) {
console.log(`POST : ${url}`);
}
return this.http.post(url, body, options).pipe(
map(response => {
return response;
}, error => {
console.error(`POST ERROR: ${url}`, error);
}));
}
Component
// Open Our formData Object
const formData = new FormData();
// Append our file to the formData object
formData.append('file', files[0]);
// POST
this.restService.postDb('files/images', formData)
.subscribe(response => {});
If I let JSON.stringify(body) when body is formData, formdata is set to {}. But if I let body like this, it throw a error 'Uncaught SyntaxError: Unexpected token o in JSON at position 1'. How can I achieve it ?

How can I submit a form doing POST of data on IONIC?

I'm trying to do a POST on ionic submitting a form with an array of data but I don't know how I can do this (but if I do this in POSTMAN, it actually works).
I tried with this form but didn't work:
submitRegistration(value):void{
var headers = new Headers();
let options = new RequestOptions({headers: headers});
headers.append("Content-Type", 'application/json');
let link = 'http://apidata.com/';
let myData = {
fos_user_registration_form: [{
_token: this.data.token,
username: value.usuario,
email: value.correo,
plainPassword: [{
first: value.password,
second: value.confirmPassword
}],
userLocalization: value.municipio}
]};
console.log(myData);
this.http.post(link, myData, options)
.subscribe(data => {
this.data.response = data["_body"];
}, error => {
alert("Oooops!");
});
}
Can anyone help me?
You have to stringify the data before you post,try this
this.http.post(link, JSON.stringify(myData), options)
.subscribe(data => {
this.data.response = data["_body"];
}, error => {
alert("Oooops!");
});
It should do the trick
Finally i find the solution (for me). Here the code
submitRegistration(value):void{
var headers = new Headers();
let options = new RequestOptions({headers: headers});
headers.append("Content-Type", 'application/x-www-form-urlencoded');
let link = 'http://APIREST.com/';
let myData = 'fos_user_registration_form[_token]='+encodeURI(this.data.token);
myData += '&fos_user_registration_form[username]='+encodeURI(value.usuario);
myData += '&fos_user_registration_form[email]='+encodeURI(value.correo);
myData += '&fos_user_registration_form[plainPassword][first]='+encodeURI(value.password);
myData += '&fos_user_registration_form[plainPassword][second]='+encodeURI(value.confirmPassword);
myData += '&fos_user_registration_form[userLocalization]='+encodeURI(value.municipio);
console.log(myData);
this.http.post(link, myData, options)
.subscribe(data => {
this.data.response = data["_body"];
console.log(data);
}, error => {
console.log("Oooops!");
});
}

Angular 2 :how to bind four services in a single call

i have referred two backend service on a success of the first service, its solved my problem for two backend services.but i have three backend services, on the success of first service, second services should call and on the success of second services, third should service call.
please help me.
service.ts
Firstservice
gethrdata(param)
{
var respone: any;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let authToken = localStorage.getItem('auth_token');
console.log(authToken);
headers.append('X-auth-Token', authToken)
return this._http.post('http://localhost:8080/ada/api/v1/client/'+param+'/hrdata', '', {headers} )
/*.map(res => res.json())*/
.map((res) => {
respone = res;
console.log(respone);
return respone;
});
}
Secondservice
getflagloa(param)
{
var respone: any;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let authToken = localStorage.getItem('auth_token');
console.log(authToken);
headers.append('X-auth-Token', authToken)
return this._http.get('http://localhost:8080/api/v1/client/'+param+'/loa', { headers })
.map(res => res.json())
.map((res) => {
respone = res;
console.log(respone);
return respone;
});
}
Thirdservice
insertloa(param)
{
var respone: any;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let authToken = localStorage.getItem('auth_token');
console.log(authToken);
headers.append('X-auth-Token', authToken);
/* let options = new RequestOptions({headers:headers});*/
return this._http.post('http://localhost:8080/api/v1/client/'+param+'/loadata', '', {headers} )
/*.map(res => res.json())*/
.map((res) => {
respone = res;
console.log(respone);
return respone;
});
}
now how can i call these services on success of prevoius service.

Angular 2 HTTP GET method not returning any header with URL

I am not getting the URL headers with a token in HTTP GET method and also GET method showing OPTION angular 2 typescripts.
Please help me.Thanks
Component.ts
onTestGet(Y)
{
var jwt = localStorage.getItem('id_token');
var k:string = localStorage.getItem(jwt);
var authHeader = new Headers();
authHeader.append('Content-Type', 'application/json');
if(k) {
authHeader.append('Authorization', 'Bearer ' + k);
}
return this._http.get('http://localhost:9095/api/v1/client/list?isClient=Y', {headers:authHeader})
.map(res => res.json())
.subscribe(
data => this.getData = JSON.stringify(data),
error => alert(error),
() => console.log("finished")
);
}