每当页面组件中的值发生更改时,如何更改导航栏中的值而不重新加载整个页面?
我从组件中获取特定值,并将其保存在本地存储中。
页面.组件.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);
}
}
即使值发生变化,导航栏中的值的控制台日志也不会更改。仅当重新加载整个页面时它才会发生变化。
最佳答案
是的,有几个选择
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.-将值存储在服务中并在需要时使用 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()
}
关于angular - 更新导航栏中的值而不重新加载整个页面 Angular 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52933294/