Angular 更新导航栏中的值,而不重新加载整个页面
当页面组件中的值发生更改时,如何在不重新加载整个页面的情况下更改navbar中的值 我从一个组件获得一个特定的值,并将其保存在本地存储器中 page.component.tsAngular 更新导航栏中的值,而不重新加载整个页面,angular,typescript,components,Angular,Typescript,Components,当页面组件中的值发生更改时,如何在不重新加载整个页面的情况下更改navbar中的值 我从一个组件获得一个特定的值,并将其保存在本地存储器中 page.component.ts getValue() { this.http.get(url) .subscribe(response => { this.value = response.value; localStorage.setItem('value', this.valu
getValue() {
this.http.get(url)
.subscribe(response => {
this.value = response.value;
localStorage.setItem('value', this.value);
}
);
}
export class NavbarComponent implements OnInit {
constructor(private router: Router, private http: HttpClient) {
this.value = localStorage.getItem('value');
console.log(this.value);
}
}
我在navbar组件中得到的值保存在本地存储中,如下所示:
navbar.component.ts
getValue() {
this.http.get(url)
.subscribe(response => {
this.value = response.value;
localStorage.setItem('value', this.value);
}
);
}
export class NavbarComponent implements OnInit {
constructor(private router: Router, private http: HttpClient) {
this.value = localStorage.getItem('value');
console.log(this.value);
}
}
navbar中值的控制台日志即使在值更改时也不会更改。只有在重新加载整个页面时,它才会更改 使用本地存储的问题是,
NavbarComponent
将读取本地存储中存储的任何内容,然后再通过HTTP请求进行更新
我建议查看可观察对象&HTTP:
您的getValue()
函数应该返回一个可观察值,NavbarComponent
可以在HTTP响应返回后订阅并更新局部变量
例如,在page.component.ts中,返回以下内容:
getValue() {
return this.http.get(url);
}
然后在navbar.component.ts中,订阅getValue()
返回的可观察值:
constructor(private page: PageComponent) {
this.page.getValue().subscribe(response => {
this.value = response.value;
});
}
嗯,有几种选择
1.-在所有组件中订阅getValue()
2.-如果组件具有父子关系,请在父级中订阅并将值传递给子级
//parent
@Component({
selector: 'app-parent',
template: `
<app-children [data]="data">
`
})
data:any
constructor(private myService:MyService){}
ngOnInit()
{
myService.getValue().subscribe(res=>
{
this.data=res
}
}
//children
@Component({
selector: 'app-parent',
template: `
{{data}}
`
})
@Input()data
//父对象
@组成部分({
选择器:“应用程序父级”,
模板:`
`
})
数据:任何
构造函数(私有myService:myService){}
恩戈尼尼特()
{
myService.getValue().subscribe(res=>
{
this.data=res
}
}
//孩子们
@组成部分({
选择器:“应用程序父级”,
模板:`
{{data}}
`
})
@Input()数据
3.-将价值存储在服务中,并在需要时使用getter
//Your service store the variable
@Injectable()
export class myService {
url="....."
data:any //<--we store the data in this variable
constructor(private httpClient:HttpClient){}
getValue() {
//Use "tap" to do something with the response
return this.httpClient.get(url).pipe(tap(res=>
{
this.data=res
}));
}
}
//In your component you use
constructor(private myService:MyService){}
get data()
{
return this.myService.data;
}
ngOnInit()
{
//You must subscribe in one and only one component, not need subscribe
//Really you can do it in the own service
myService.getValue().subscribe()
}
//您的服务存储变量
@可注射()
导出类myService{
url=“…”
数据:任何//
{
this.data=res
}));
}
}
//在您使用的组件中
构造函数(私有myService:myService){}
获取数据()
{
返回this.myService.data;
}
恩戈尼尼特()
{
//您必须订阅一个且仅订阅一个组件,而不需要订阅
//你真的可以自己做吗
myService.getValue().subscribe()
}
您能举例说明如何使用可观测值吗?