how to manipulate localStorage parameters in ionic 2 i get undefined values - json

i have struggles with the local storage parameter i have this //error SyntaxError at JSON.parse ()// i get " undefined" instead of the real values any help please on how to retrieve parameters from LocalStorage that i set after login in both my service auth-service.ts and auth.ts??!!
auth-service.ts
public loginChef(credentials) {
if (credentials.email === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
return Observable.create(observer => {
var url = 'http://localhost/PFEBACKEND/login-chef.php?
email='+credentials.email+'&passe='+credentials.password ;
this.http.get(url).map(res => res.json()).subscribe(
data=>{
let access = (data.error=== 0 )
localStorage.setItem('nom',data.nom_contact);
localStorage.setItem('nom_societe',data.nom_societe);
localStorage.setItem('email',data.email);
localStorage.setItem('telephone',data.telephone);
localStorage.setItem('matricule_fiscale',data.matricule_fiscale);
localStorage.setItem('role',data.role);
localStorage.setItem('id',data.id_chef);
this.member=data;
this.email=data.email;
this.nom=data.nom;
// this.currentUser = new User( data.nom,data.email);
observer.next(this.email,this.nom);
//observer.next(this.member);
//observer.next(access);
// console.log(this.currentUser);
observer.complete();
},
err => {
console.log(err);
observer.next(err);
},
() => console.log('service observable') );
});
}
}
offre.ts
offres: Array<any>;
loader: any;
id:string='';
constructor(public navCtrl: NavController, public navParams: NavParams,
public data:Datamembers,private auth:AuthService, public
loadingCtrl:LoadingController)
{
if(localStorage.getItem('id')){//after login i store the user data
this.id=localStorage.getItem('id');
}
}
ngOnInit()
{ var id1=parseInt(this.id).valueOf();// i get undefined value
this.presentLoading();
this.data.LoadOffres(id1).subscribe(
//function LoadOffres accept int type parameter
data => {
this.offres = data;
console.log(data);
this.loader.dismiss();
},
err => {
console.log(err);
console.log(id1);
this.loader.dismiss();
},
() => console.log('chargement terminé')
);
}
auth.ts
public loginChef() {
this.showLoading();
this.auth.loginChef(this.registerCredentials).subscribe(allowed => {
if (allowed) {
setTimeout(() => {
this.email=this.auth.email;
this.nom=this.auth.nom;
this.currentUSer = this.auth.currentUser;
this.member=this.auth.member;//array
localStorage.setItem('email',this.email);
localStorage.setItem('nom',this.nom);
(....)

everything is right the problem was in my server side code

Related

how can I do login form for angular?

I am trying to create a login form for my website. I'm using agular , express and mongoDB
Here's my controller of login function:
loginUser: (req, res) => {
User.findOne({
username: req.body.login_username
})
.then(user => {
bcrypt.compare(req.body.login_password, user.password)
.then(result => {
if (result) {
req.body.login_username = user.username
res.json({
message: "Success!",
added: true
});
} else {
console.log('Failed login attempt')
res.json({
message: "Error!",
error: err
});
}
}).catch(console.error, console.log(req.body.login_password, user.password))
})
}
and here is my login components:
userID: string;
userData: any;
loginUser: any;
error = "";
constructor(
private router: Router,
private route: ActivatedRoute,
private httpService: HttpService
) {}
ngOnInit() {
this.userID = this.route.snapshot.paramMap.get("id");
this.getSingleUser();
this.loginUser = { username: "", password: "" };
}
getSingleUser() {
let observable = this.httpService.getOneUser(this.userID);
observable.subscribe((data) => {
this.userData = data;
});
}
onSubmit() {
let observable = this.httpService.loginUser(this.loginUser);
observable.subscribe((data: any) => {
console.log("Wrong");
if (data.error) {
this.error = data.error.errors.name.message;
} else {
this.getSingleUser();
this.router.navigate([""]);
}
});
}
When I click on button my terminal getting an error like this:
undefined $2b$20$8DmOjsDm3h5q/jEq9lNauezUdFYdL6EBt9gjmCu8/0DU0kAnSSIA2
Error: data and hash arguments required
at Object.compare (/Users/nhannguyen/Desktop/personal_project/instagram/node_modules/bcrypt/bcrypt.js:208:17)
at /Users/nhannguyen/Desktop/personal_project/instagram/node_modules/bcrypt/promises.js:29:12
at new Promise ()
at Object.module.exports.promise (/Users/nhannguyen/Desktop/personal_project/instagram/node_modules/bcrypt/promises.js:20:12)
at Object.compare (/Users/nhannguyen/Desktop/personal_project/instagram/node_modules/bcrypt/bcrypt.js:204:25)
at /Users/nhannguyen/Desktop/personal_project/instagram/server/controllers/users.js:65:24
at processTicksAndRejections (internal/process/task_queues.js:97:5)
Please add .catch(console.error) after the .then() to catch the full error.
After that check if the values are really there and if not, check if the body-parser plugin is installed

Cannot access value of a json object ? Cannot read property 'company_about' of undefined ?

This is my JSON
[
{
"id": 1,
"job_id": 1,
"company_profile": "Sales and Marketing",
"company_about": "Established in 1992 , it is a renouned marketing company",
"company_product": "Ford,Mustang,Beetle",
"key_skills": "commmunication,english,spanish,german",
"qualification": "High School,Masters",
"job_description": "Must be a Local of Mumbai",
"created_at": null,
"updated_at": null
}
]
I am trying to get its values.
this is my react code to log them.
public getJobDetails = (jobid: number) => {
const JobId = jobid;
fetch('http://127.0.0.1:8000/api/jobs/detail/' + JobId)
.then(response => response.json())
.then(
responseJson => {
console.log(responseJson);
this.setState({ details: responseJson });
},
() => {
console.log(this.state.details);
}
)
.catch(error => {
console.error(error);
});
}
public render() {
const { details } = this.state;
console.log(details);
console.log(details[0]);
The console.log(details[0]) returns
{id: 1, job_id: 1, company_profile: "Sales and Marketing", company_about: "Established in 1992 , it is a renouned marketing company", company_product: "Ford,Mustang,Beetle", …}
But why does console.log(details[0].company_profile) return undefined???
The Error it gives is :
TypeError: Cannot read property 'company_about' of undefined
can anyone help??
Use a conditional statement in your render so that if your request isn't complete and your state doesn't have details yet it doesn't load anything.
Edit --- Sample Code (not your application, but concept of what I mean)
import React, { Component, Fragment } from 'react';
export class App extends Component {
constructor(){
super()
this.state = {
data: [],
isLoading: true
}
}
componentWillMount(){
this.fetchDetails()
}
fetchDetails = () =>{
fetch('/some/url')
.then(res => res.json())
.then( => {
this.setState({data, isLoading: false})
})
}
render() {
return (
<Fragment>
{!this.state.isLoading && <ChildComponent data={this.state.data}} />}
</Fragment>
);
}
}
Try more logging, e.g.:
public getJobDetails = (jobid: number) => {
const JobId = jobid;
fetch('http://127.0.0.1:8000/api/jobs/detail/' + JobId)
.then(response => response.json())
.then(
responseJson => {
console.log(`Fetch resulted in ${JSON.stringify(responseJson)}`);
this.setState({ details: responseJson });
},
() => {
// This line is supposed to act as error handler, but there is no error handling
// See this - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then#Syntax
console.log(this.state.details);
}
)
.catch(error => {
console.error(`Fetch resulted in error ${JSON.stringify(error)}`);
});
}
public render() {
const { details } = this.state;
console.log('Rendering...');
console.log(`step 1. ${JSON.stringify(details)}`);
// let's see if details are not undefined and try next level
details && console.log(`step 2. ${JSON.stringify(details[0])}`);
Your fetch code is asynchronous and you don't have a default value set for this.state You can try a couple different options. You could redefine getJobDetails to return the promise rather than changing the state:
class MyComponent extends React.Component {
public getJobDetails = (jobid: number) => {
const JobId = jobid;
return fetch('http://127.0.0.1:8000/api/jobs/detail/' + JobId)
}
public render() {
this.getJobDetails().then(response => {console.log(response[0])})
}
}
Or you can set a default state
class MyComponent extends React.Component {
public state = {
details: [...]
}
}
EDIT
Performing a network request every render cycle is not very efficient, so it's probably not the best route to go. I also forgot a third option, conditional rendering like this:
class MyComponent extends React.Component {
state = { loading: true }
getJobDetails = (jobid: number) => {
fetch(...).then((response) => {
this.setState({details: response})
this.setState({loading : false})
})
}
render() {
return this.state.loading ? <h1>Loading...</h1> : <div>{this.state.deatils}</div>
}
}
Also you should not be converting your data to JSON if you want to access it as an Object

Using a service in angular 4 guards

Please assist with angular guards, I have the following angular Guard below :
export class RoleGuard implements CanActivate {
private role: any;
constructor(private router: Router, private accountService: AccountService)
{}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
this.accountService.getUserRole().subscribe(res => this.role = res);
if (this.role === 'admin') {
return true;
}
return false;
}
}
in the service:
getUserRole(): Observable<Response> {
const options = this.headers();
return this.http.get(`${environment.ApiUrl}/Roles/getRole`,options)
.map(res => res.json())
.catch(res => Observable.throw(res.json()));
}
I am trying to subscribe to the getUserRole() function, then assign the response to this.role but that is not happening, role is always undefined. when i do a ...subscribe(res => console.log(res)) i see the response data.
You have to wait the result of the async HTTP Request before check if can activate that route or not.
Try returning a new Observable instead:
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
return new Observable(observer => {
//
this.accountService.getUserRole().subscribe(role => {
//
if (role === 'admin') {
observer.next(true); // Allowing route activation
} else {
observer.next(false); // Denying route activation
}
}, err => observer.next(false));
});
}

Angular2 Authentication : there's something wrong with POST request?

Hi I am trying to authenticate users and once the server gives user's information, I want to use the information of the user.
But for some reasons, even though I did the log in process without any error and I can see from developer's tool that the POST request has been successful, I can't quite set currentUser in my localStorage (giving me null if I console.log it)
What am I doing wrong?
This is my authentication service.
export class AuthenticationService {
constructor(private http: Http, private router: Router) { }
login(email: string, password: string): Observable<User>{
const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append('Access-Control-Allow-Methods', 'post');
headers.append('Access-Control-Allow-Origin', '*');
headers.append("X-Requested-With", "XMLHttpRequest");
let options = new RequestOptions({ headers: headers });
let body = new URLSearchParams();
body.set('email', email);
body.set('password', password);
return this.http.post(`${environment.baseurl}` + '/api/v2/member/login', body, options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let user = res.json();
if (user && user.token) {
localStorage.setItem('currentUser', JSON.stringify(user));
}
return user.data || {};
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
}
private handleError(error: any) {
if (error.status === 401) {
return Observable.throw(error.status);
} else {
return Observable.throw(error.status || 'Server error');
}
}
}
And this is my log-in component
export class LoginPageComponent implements OnInit {
constructor(private location: Location,
private route: ActivatedRoute,
private router: Router,
private authenticationService: AuthenticationService,
private alertService: AlertService) {
}
model: any = {};
loading = false;
returnUrl: string;
error = '';
ngOnInit() {
// get return url from route parameters or default to '/'
this.returnUrl = this.route.snapshot.queryParams['main'] || '/';
}
currentUser: User;
login() {
this.loading = true;
this.authenticationService.login(this.model.email, this.model.password)
.subscribe(
data => {
this.currentUser = data;
this.router.navigate([this.returnUrl]);
},
error => {
this.error = "Wrong ID or PW";
this.loading = false;
});
}
backClicked() {
this.location.back();
}
}
And this is my home component
export class MainComponent {
onClick() {
this.auth.logout() //if user clicks logout button
}
currentUser: User;
users: User[] = [];
items: Object[] = [];
constructor(private authguard: AuthGuard, private auth:AuthenticationService) {
this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
console.log(localStorage.getItem('currentUser')); //Printing null
}
}
And the model for user information is this.
export interface User {
birthday: number;
email:string;
genderType:string;
memberType: string;
name: string;
phone: string;
}
What im receiving
Why is it printing null?
Thank you!
Mistakes you made
passing email and password as URLSearchParams.
You are adding all the headers to your login method which is not necessary
The service should contain method as below
login(body: any, options?: RequestOptionsArgs): Observable<Response> {
return this.http.post('loginUrl', body);
}
Component should contain the below code
login() {
let user ={
email : this.model.email
password : this.model.password)
}
this.loading = true;
this.authenticationService.login(user)
.subscribe(data => {
this.authenticationService.extractData(data);///call to store token in the localstorage
this.router.navigate([this.returnUrl]);
},
error => {
this.error = "Wrong ID or PW";
this.loading = false;
});
}

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.