I am having trouble updating my view. In ngOnInit I am resolving a promise. If it cannot do the HTTP request (ie there is no internet) then the catch should look into local storage to find the user and display the information in the view.
Important: It just doesn't work when I redirect the user from the login page to the home page using .navigate. If I reload the component once in home page it does work.
What am I doing wrong?
This is the code in the home page component:
ngOnInit() {
this.mySession.isLoggedIn()
// make request to server via HTTP
.then( userInfo => {
// if request successful do:
this.user = userInfo;
this.user2 = userInfo;
if(this.user.searchbar === false) {
$('#searchbar').prop('checked', false);
} else if(this.user.searchbar) {
$('#searchbar').prop('checked', true);
}
})
// if request via HTTP fails do:
.catch(() => {
// find user in Local Storage and set it equal to this.user;
this.getLocalUser();
console.log('catch within home component');
});
}
getLocalUser() {
chrome.storage.sync.get(this.signupInfo,(response) => {
this.user = {};
this.user = response;
this.user2 = response;
console.log('this.user: ');
console.log(this.user);
if(this.user.searchbar === false) {
$('#searchbar').prop('checked', false);
} else if(this.user.searchbar) {
$('#searchbar').prop('checked', true);
}
});
}
This is my HTML-Template within the home page component:
<h4>
<div id="firstGreeting" class="greeting">Good Day, {{ user.firstName }}.</div>
<span class="highlight disappear">How is your day going?</span>
<div class="highlight second">Do you mind telling why?</div> <br>
<span class="forMonth"> - {{ stringMonth }} - </span>
</h4>
This is the code within the login component that redirects to from the login to the home page:
signup() {
const thePromise = this.mySession.signUp(this.signupInfo);
thePromise.then(userInfo => {
console.log('User was saved in the server');
// Save user to Local Storage using Chrome API
chrome.storage.sync.set(this.signupInfo, () => {
// Notify that we saved.
console.log('User was saved locally in the pc');
this.myNavigator.navigate(['home']);
return;
});
});
thePromise.catch((err) => {
this.error = err;
console.log(this.error)
});
}
You code has a reference issue. Here 'this' in function(response) is a reference of function(response). You may use Arrow Functions or let that = this outside function and use that inside function.
getLocalUser() {
chrome.storage.sync.get(this.signupInfo, (response) => {
this.user = {};
this.user = response;
this.user2 = response;
console.log('this.user: ');
console.log(this.user);
if(this.user.searchbar === false) {
$('#searchbar').prop('checked', false);
} else if(this.user.searchbar) {
$('#searchbar').prop('checked', true);
}
});
If this does not work, please post your template.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.