繁体   English   中英

Angular2双向绑定停止工作

[英]Angular2 Two-Way-Binding stopped working

我无法更新自己的观点。 在ngOnInit中,我正在履行诺言。 如果它不能执行HTTP请求(即,没有互联网),则捕获应查找本地存储以查找用户并在视图中显示信息。

重要提示:当我使用.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”是功能(响应)的引用。 您可以使用箭头函数,也可以使用=外部函数并使用内部函数。

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);
   }
});

如果这不起作用,请发布您的模板。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM