当页面组件中的值发生更改时,如何在不重新加载整个页面的情况下更改导航栏中的值?
我从组件中获得了一定的值,并将其保存在本地存储中。
page.component.ts
getValue() {
this.http.get(url)
.subscribe(response => {
this.value = response.value;
localStorage.setItem('value', this.value);
}
);
}
我正在获取navbar组件中的值,该值保存在本地存储中,如下所示: navbar.component.ts
export class NavbarComponent implements OnInit {
constructor(private router: Router, private http: HttpClient) {
this.value = localStorage.getItem('value');
console.log(this.value);
}
}
即使值更改,导航栏中值的控制台日志也不会更改。仅当重新加载整个页面时,它才会更改。
答案 0 :(得分:1)
使用本地存储的问题是NavbarComponent
将在HTTP请求更新之前读取本地存储中存储的任何内容。
我建议您查看Observables和HTTP:https://angular.io/guide/http
您的getValue()
函数应返回一个Observable,一旦HTTP响应返回,NavbarComponent
就可以订阅并更新本地变量。
例如,在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 :(得分:1)
是的,有几个选择
1.-在所有组件中订阅getValue()
//You has a service
@Injectable()
export class myService {
url="....."
constructor(private httpClient:HttpClient){}
getValue() {
return this.httpClient.get(url);
}
}
//In each component you need subscribe to getValue
//component1
constructor(private myService:MyService){}
ngOnInit()
{
myService.getValue().subscribe(res=>
{
..do something..
}
}
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
3.-将值存储在服务中,并在需要时使用吸气剂
//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()
}