angular - 更新导航栏中的值而不重新加载整个页面 Angular 4

标签 angular typescript components

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

我从组件中获取特定值,并将其保存在本地存储中。

页面.组件.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/

相关文章:

typescript - 我们如何获得TypeScript的语法树?

c# - 添加新组件以及什么是 Interop.dll 文件?

css - 应用默认样式和 onClick 更改按钮的样式-Angular 4

angular - NGXS:有没有办法在一个 Action 完成后返回一个特定的值

javascript - Angular 4 jquery 不起作用

mysql - Angular 4 与 Nodejs 和 Mysql 连接

angular - 比较 Observable 的前一个值和 Angular 中的下一个值

javascript - 无法读取未定义的属性 '0' - Angular 6 和 Angular Material - mat-radio-group [(ngModel)] 在 *ngFor 内设置动态变量

javascript - Angular 2+ 对调用 httpclient get 的服务进行单元测试

components - 使用 TOM.NET 更新多媒体组件