angular - 更新导航栏中的值而不重新加载整个页面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);
}
}
即使值更改,导航栏中的值的控制台日志也不会更改。只有在重新加载整个页面时它才会改变。
解决方案
使用本地存储的问题在于它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;
});
}
推荐阅读
- amazon-web-services - 将基本域 url(例如没有 www 的 site.com)配置到 api 网关,并使其在浏览器中工作
- python-3.x - tensorflow-probability: AttributeError: Tensor.op 在启用急切执行时毫无意义
- groovy - 执行脚本时出现异常:[{}]java.lang.NullPointerException:无法在空对象上获取属性“httpResponse”
- scala - 我将如何根据一列或另一列是否匹配案例在 Scala 中执行联接?
- html - 列表中的链接标题呈现在导航栏中的链接下方
- java - 2048 Java 游戏:移动功能
- spring-boot - spring boot gradle任务“bootBuildImage”构建的cloudfoundry buildpack docker镜像中的语言环境和编码设置如何
- python - 属性错误:“sage.rings.polynomial.skew_polynomial_element.SkewPolynomial_generic_de\ nse”对象没有属性“因子”
- javascript - 如何从异步函数返回值?
- laravel - 找不到注入清单的地方