首页 > 解决方案 > 更新导航栏中的值而不重新加载整个页面Angular 4

问题描述

每当页面组件中的值发生更改而不重新加载整个页面时,如何更改导航栏中的值?

我从组件中获得了一定的价值,并将其保存在本地存储中。

page.component.ts

  getValue() {
    this.http.get(url)
        .subscribe(response => {
          this.value = response.value;
          localStorage.setItem('value', this.value);
        }
      );
    }

我正在获取保存在本地存储中的导航栏组件中的值,如下所示:navbar.component.ts

  export class NavbarComponent implements OnInit {

    constructor(private router: Router, private http: HttpClient) {

      this.value =  localStorage.getItem('value');
        console.log(this.value);

      }
 }

即使值更改,导航栏中的值的控制台日志也不会更改。只有在重新加载整个页面时它才会改变。

标签: angulartypescriptcomponents

解决方案


使用本地存储的问题在于它NavbarComponent会在 HTTP 请求更新之前读取存储在本地存储中的任何内容。

我建议查看 Observables 和 HTTP:https ://angular.io/guide/http

你的getValue()函数应该返回一个 Observable,NavbarComponent一旦 HTTP 响应返回,它就可以订阅并更新一个局部变量。

例如,在 page.component.ts 中,返回以下内容:

getValue() {
    return this.http.get(url);
}

然后在 navbar.component.ts 中订阅getValue()返回的 observable:

constructor(private page: PageComponent) {
    this.page.getValue().subscribe(response => {
        this.value = response.value;
    });
}

推荐阅读