我无法更新自己的观点。在ngOnInit我正在解决一个承诺。如果它无法执行HTTP请求(即没有互联网),那么catch应该查看本地存储以查找用户并在视图中显示信息。
重要提示:当我使用.navigate将用户从登录页面重定向到主页时,它无法正常工作。如果我在主页上重新加载一次该组件,它确实有效。
我做错了什么?
这是主页组件中的代码:
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);
}
});
}
这是我在主页组件中的HTML模板:
<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>
这是登录组件中重定向到登录主页的代码:
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)
});
}
答案 0 :(得分:1)
您的代码存在参考问题。函数(响应)中的'this'是函数(响应)的引用。你可以使用Arrow Functions或者让那个=这个外部函数并使用它的内部函数。
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);
}
});
如果这不起作用,请发布您的模板。