Convert Promise object to JSON in Angular 2 - json

I'm trying to make an HTTP POST and then check the response to see if it fails or succeeds.
The HTTP call looks like this :
doLogin(credentials) {
var header = new Headers();
header.append('Content-Type', 'application/x-www-form-urlencoded');
var body = 'username=' + credentials.username + '&password=' + credentials.password;
return new Promise((resolve, reject) => {
this.http.post(this.url, body, {
headers: header
})
.subscribe(
data => {
resolve(data.json());
},
error => {
resolve(error.json());
}
);
});
}
And the call of this function is the following :
data: Object;
errorMessage: Object;
login($event, username, password) {
this.credentials = {
username: username,
password: password
};
this._loginService.doLogin(this.credentials).then(
result => {
this.data = result;
console.log(this.data);
},
error => {
this.errorMessage = <any>error;
console.log(this.errorMessage);
});
}
On Chrome console, the data is the following :
Object {status: "Login success", token: "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJjcmlzdGkiLCJ1c2VyS…blf1AzZ6KzRWQFNGXCrIeUHRG3Wrk7ZfCou135WmbVa15iYTA"}
How can I access the status in Angular 2? Because if I'm trying to access this.data.status, it's not working.
Should I create a class with the status and token properties?

To answer your question, you can use the response.okboolean that's available in the subscription of the observable from the http.
So based on your code you could pass the data object straight to the promise and inspect data.ok before parsing the data.json.
//...
return new Promise((resolve, reject) => {
this.http.post(this.url, body, {
headers: header
})
.subscribe(resolve,
error => {
reject(error.json());
}
);
});
// then you would have something like this:
this._loginService.doLogin(this.credentials).then(
result => {
if (result.ok) {
this.data = result;
console.log(this.data);
}
},
error => {
this.errorMessage = <any>error;
console.log(this.errorMessage);
})
SUGGESTION
Now, I would recommend getting rid of the promise, as I believe you don't really need it. whoever is consuming your service can just subscribe to the observable returned by the http post, like so:
doLogin(credentials) {
let header = new Headers();
header.append('Content-Type', 'application/x-www-form-urlencoded');
var body = 'username='+credentials.username+'&password='+credentials.password;
return this.http.post(this.url, body, { headers: header });
}
Then, when logging in:
login($event, username, password) {
this.credentials = {
username: username,
password: password
};
this._loginService.doLogin(this.credentials).subscribe(response => {
if (response.ok) { // <== CHECK Response status
this.data = response.json();
console.log(this.data);
} else {
// handle bad request
}
},
error => {
this.errorMessage = <any>error;
console.log(this.errorMessage);
});
}
Hope this helps!

You could do it like this:
data: Object;
errorMessage: Object;
login($event, username, password) {
this.credentials = {
username: username,
password: password
};
this._loginService.doLogin(this.credentials).then(
(result: any) => {
this.data = result;
console.log(this.data);
console.log(this.data.status);
},
error => {
this.errorMessage = <any>error;
console.log(this.errorMessage);
});
}
Set the result to type any. That way you'll be able to access the status, however you could create a class and use rxjs/map within your service to populate the class if you so desire.

Related

My response from api is undefined on frontend

I got list of items from my database mySql and also button 'edit'.
When I clicked edit (by id) I want to see all fields filled by data.
But I only have in my console: undefined
If I tested my api by postman it works fine.
There is how I am getting list.
{
const id = this.actRoute.snapshot.paramMap.get('id');
this.studentApi.GetStudent(id).subscribe((res: any) => {
console.log(res.data);
this.subjectArray = res.data;
console.log(this.subjectArray);
this.studentForm = this.fb.group({
id: [res.id, [Validators.required]],
domain_id: [res.domain_id, [Validators.required]],
source: [res.source, [Validators.required]],
destination: [res.destination]
});
});
}
There is my api.service.ts
GetStudent(id): Observable<any> {
const API_URL = `${this.endpoint}/read-student/${id}`;
return this.http.get(API_URL, { headers: this.headers })
.pipe(
map((res: Response) => {
return res || {};
}),
catchError(this.errorMgmt)
);
}
And there is my route
studentRoute.get('/read-student/:id', (request, response) => {
const id = request.params.id;
con.query('SELECT * FROM students WHERE id = ?', id, (error, result) => {
if (error) throw error;
response.send(result);
});
});
There is response from 'postman'
[
{
"id": 5,
"domain_id": 2,
"source": "tester0700#test.pl",
"destination": "testw#test.pl"
}
]
It seems like the response is an array, containing an object.
In that case, there is no need to use res.data, as that would imply the returned observable, res has a property named data, and that you are trying to access the value within that property. You can simply assign res to the subjectArray property. I am pretty sure res would be defined.
this.studentApi.GetStudent(id).subscribe((res: any) => {
console.log(res);
this.subjectArray = res;
// handle the rest here.
});

Changed request does not work in angular 6

I have following function which calls the refresh service to get new token for authorization:
private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
if(!this.isRefreshingToken) {
this.isRefreshingToken = true;
return this.authService.refreshToken()
.subscribe((response)=> {
if(response) {
const httpsReq = request.clone({
url: request.url.replace(null, this.generalService.getUserId())
});
return next.handle(this.addTokenToRequest(httpsReq, response.accessToken));
}
return <any>this.authService.logout();
}, err => {
return <any>this.authService.logout();
}, () => {
this.isRefreshingToken = false;
})
} else {
this.isRefreshingToken = false;
return this.authService.currentRefreshToken
.filter(token => token != null)
.take(1)
.map(token => {
return next.handle(this.addTokenToRequest(request, token));
})
}
}
When the response is not undefined and request is returned back it does not call the new request
Ok the thing was that the bearer was quoted like below:
But I have still one issue the request does not invoke the new request, when I refresh the page it gives data with new token, instead like I previously had unauthorized error.

Angular 6 AWS Cognito How to Handle newPasswordRequired

I am completely at a loss here. I have been struggling with this for several hours now trying multiple different approaches and none are getting me anywhere. My problem is I cannot seem to figure out how it the new Password is meant to be retrieved from the user within the newPasswordRequired callback after an authentication request to Cognito. Here is my code in its current state. Please don't hesitate to tell me what I can do better, as I am fairly new to Angular and completely new to using Cognito authentication.
public login(email: string, password: string): Observable<UserModel> {
const cognitoUser = new CognitoUser(this.getUserData(email));
cognitoUser.setAuthenticationFlowType('USER_PASSWORD_AUTH');
const authenticationDetails = new AuthenticationDetails(CognitoUtils.getAuthDetails(email, password));
const self = this;
return Observable.create((obs: Observer<UserModel>) => {
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: result => {
this.session = result;
const token = result.getIdToken();
const accessToken = result.getAccessToken();
this.localStorage.setToken(token);
this.localStorage.setAccessToken(accessToken);
obs.complete();
},
onFailure: err => {
obs.error(err);
},
newPasswordRequired: (userAttributes, requiredAttributes) => {
let dialogRef: MatDialogRef<NewPasswordComponent>;
const config = new MatDialogConfig();;
config.role = 'dialog';
config.width = '40%';
config.data = { newPass: self.newPass };
dialogRef = self.dialog.open(NewPasswordComponent, config);
dialogRef.afterClosed().subscribe(result => {
self.newPass = result;
cognitoUser.completeNewPasswordChallenge(self.newPass, userAttributes, {
onSuccess: result => {
obs.complete();
},
onFailure: err => {
obs.error(err);
}
});
});
}
});
});
}
Based on what you have provided, it looks like the issue is when you respond with completeNewPasswordChallenge you're passing in userAttributes which is returned from the newPasswordRequired callback and won't work.
Instead, you need to see what attributes are required (i.e. requiredAttributes) and pass them in as an object. For example, if "name" is the required attribute, then pass in the following way:
dialogRef.afterClosed().subscribe(result => {
self.newPass = result;
cognitoUser.completeNewPasswordChallenge(self.newPass, {"name":"John Doe"}, {
onSuccess: result => {
obs.complete();
},
onFailure: err => {
obs.error(err);
}
});
Hope this helps!

ionic2 Property does not exist on type '{}'

I am getting a json in typescript in ionic framework.
The json is:
{
"result": "success",
"user": {
"loggedIn": true,
"name": "Nulra",
"password": ""
}
}
And I print the data:
console.log("NULRA CHECKING: " + data.result + " " + data.user);
It gives the error:
Typescript Error
Property 'result' does not exist on type '{}'.
Property 'user' does not exist on type '{}'.
auth-service.ts:
login(credentials) {
let opt: RequestOptions;
let myHeaders: Headers = new Headers;
myHeaders.set('Accept', 'application/json; charset=utf-8');
myHeaders.append('Content-type', 'application/json; charset=utf-8');
opt = new RequestOptions({
headers: myHeaders
})
return new Promise((resolve, reject) => {
this.http.get(apiUrl+'login/0/login?email='+credentials.email+'&password='+credentials.password, opt)
.map(res => res.json())
.subscribe(data => {
this.data = data;
resolve(this.data);
},(err) => {
reject(err);
});
});
}
In login.ts:
doLogin(){
this.authService.login(this.loginData)
.then(data => {
console.log("NULRA CHECKING: " + data.result + " " + data.user);
}
.catch(err => {
});
}
Anyone know how to deal with it? because the json I confirmed have result and user. Thanks a lot.
when console.log(data):
Try this-
public userData: any = {};
doLogin(){
this.authService.login(this.loginData)
.then(data => {
this.userData = data;
console.log(`NULRA CHECKING: ${this.userData.result} ${this.userData.user}`);
}
.catch(err => {
});
}
Well, I got this solved when I simple called data['result'] instead of data.result;
For me it appeared only when i first executed ionic serve.

Angular 2:Not able to get a token in another component which is stored in local storege

I have one application which include login and home component,
login.service.ts
let body = JSON.stringify(data);
console.log("logged in user",body);
return this._http.post('http://localhost:8080/api/user/authenticate', body, { headers: contentHeaders })
.map(res => res.json())
.map((res) => {
var token1:any = res;
console.log(token1);
if (token1.success) {
localStorage.setItem('auth_token', token1.token);
this.LoggedIn = true;
}
return res.success;
});
}
isLoggedIn() {
return this.LoggedIn;
}
in this service i am getting token in variable token1 and isLogged method contain
constructor(private _http: Http) {
this.LoggedIn = !!localStorage.getItem('auth_token'); }
Login.component.ts
login(event, username, password)
{
this.loginService.login(username, password)
.subscribe(
response => {
this.router.navigate(['/home']);
alert("login successfull");
},
error => {
alert(error.text());
console.log(error.text());
}
);
From this login i can able to authenticate and and its routing to home component,
Home.serice.ts
getClientList()
{
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let authToken = localStorage.getItem('auth_token');
headers.append('X-auth-Token', 'authToken')
return this._http.get('http://localhost:8080/api/v1/client/list?isClient=Y', {headers})
.map(res => res.json())
}
Home.component.ts
onTestGet()
{
this._httpService.getClientList()
.subscribe(
data => this.getData = JSON.stringify(data),
error => alert(error),
() => console.log("finished")
);
}
now question is how can i access that token in home component which is in token1 varible(login) i have tired to getitem token.but i am getting token null.please anybody help me.
thanks in advance
localStorage.getItem('auth_token')
This should work, but you are getting null, because lifecycle of the data different.
I suggest you to use Subject construction for this purpose, especially you already have service with data.
Example:
loginInfo$ = new Subject();
private _logininfo = null;
getLoginData () {
if(!_logininfo) {
this.http..... { this._loginInfo = data;
this.loginInfo$.next(data); }
return this.loginInfo$.first()
}
else return Observable.of(this._logininfo);
}
So now, your service at the same time storage of data and handler for missing login.