Hi guys, I need your help
I got this code example around, I dont remenber
I dont know if this code is good
service-provider.ts
export class ServiceProvider {
api: string = 'https://www.mydomine/api/v1/';
isLoggedIn = false;
AuthToken: string;
constructor(public http: Http) {
this.isLoggedIn = false;
this.AuthToken = null;
}
// Authenticate and verify email and password of User and create TOKEN
authenticate(user) {
let creds = 'email=' + user.email + "&password=" + user.password;
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
return new Promise(resolve => {
this.http.post(this.api+'auth', creds, {headers: headers}).subscribe( data => {
if(data.json().success){
this.storeUserCredentials(data.json().success);
resolve(true);
}
else
resolve(false);
});
});
}
// Get the token and send to userCredentials method bellow
storeUserCredentials(token) {
window.localStorage.setItem('token', token);
this.useCredentials(token);
}
useCredentials(token) {
this.isLoggedIn = true;
this.AuthToken = token;
}
loadUserCredentials() {
let token = window.localStorage.getItem('token');
this.useCredentials(token);
}
// Destroy Authentication of User
destroyUserCredentials() {
this.isLoggedIn = false;
this.AuthToken = null;
window.localStorage.clear();
}
createAuthorization(headers: Headers) {
headers.append('Authorization', window.localStorage.getItem('token'));
}
getCauses() {
return this.http.get(this.api+'causes').map( res => res.json());
}
}
I’m doing login and get the token of my API, but I dont know to use TOKEN in other places, for example in getCauses method
I want resolve by steps
1 - To use TOKEN in others requests using Headers Authorization + Beares + Token
2 - To use TOKEN to call forever user logged in all pages
It will automatically send your token and authorization header along with requests if you use this.authHttp.get and it has lots of helper functions like isTokenExpired()
If you want to do it like you have it, it would be something like this
let headers = new Headers({ 'Authorization': 'Bearer ' + window.localStorage.getItem('token') });
let options = new RequestOptions({ headers: headers });
return this.http.get(this.api+'causes', options).map( res => res.json());
I’m not sure what you are asking in the second question
@nb1990 Sorry if I asked you wrong, I want to use the data of user logged, example, wellcome {{ user->name }}, other example, to use data of user logged to edit and update in myProfileComponent.ts for example, its ok now friend ?
return this.http.get(this.api+'causes', options).map( res => res.json());
this is return Error:
Cannot find a differ supporting object ‘[object Object]’ of type ‘object’. NgFor only supports binding to Iterables such as Arrays.
return a object
if I use this
return this.http.get(this.api+'causes' + options).map( res => res.json());