Angular2双向绑定停止工作
我在更新视图时遇到问题。在ngOnInit我正在解决一个承诺。如果它不能执行HTTP请求(即没有互联网),那么catch应该查看本地存储来查找用户并在视图中显示信息。Angular2双向绑定停止工作
重要提示:使用.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)
});
}
您的代码有一个参考问题。函数(响应)中的'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);
}
});
如果这不起作用,请发布您的模板。
谢谢你的时间!我实际上尝试了箭头功能,它不起作用。我添加了一些可能有用的额外信息。再次感谢你的帮助。 :) –
什么是'myNavigator'?你能显示你的路由设置吗? – wannadream
不是您的问题的答案,但您应该考虑将离线代码抽象到您的'mySession'服务中,以便它从HTTP请求或脱机缓存中返回用户信息,以便组件不可见。这样你就不会在'getLocalUser()'函数中重复你的代码。 –
对于这个问题,目前还不清楚你的'ngOnInit'函数和'signup'函数之间的关系是什么,也不知道'ngOnInit'的位置。在登录页面上?在主页上? –
@MikeMcCaughan我编辑我的答案更加明确!并感谢您的反馈。我目前正在重构我的代码,并会按照您的说法进行操作。谢谢! –