【问题标题】:Angular - How to share an app variable with all componentsAngular - 如何与所有组件共享应用程序变量
【发布时间】:2019-03-16 21:10:40
【问题描述】:

我正在制作一个小应用程序,前面有 Angular7,背面有 Flask,我要做的是订阅服务,然后将返回的数据保存到我的主 AppComponent 内部的对象类型变量中,然后在我的所有其他组件中访问此变量。

API 服务

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http: HttpClient) { }

  CheckApi(){
    return this.http.get('http://localhost:5000/')
  }

}

应用组件

import { Component, OnInit, Injectable } from '@angular/core';
import { ApiService } from './api.service'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {

  title = 'Inbox App';

  public text: object

  constructor(private data: ApiService){}

  ngOnInit(){
    this.data.CheckApi().subscribe(data => {
        this.text = data
        console.log(this.text)
    })
  }
}

这是我试图从另一个组件中访问该对象的地方:

登录组件

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

login.component.html

<section>
    <legend class="text-center">{{ text }}</legend>
</section>

【问题讨论】:

  • 这是一个工作示例stackblitz.com/edit/angular-hq3uam
  • @JasonWhite,感谢您的关注,但为什么 this.apiService.data; 返回 Observable 对象而不是来自服务器的数据?
  • 我没有服务可以使用,你可以在CheckApi方法中放一个http调用并获取数据。我注释掉了 api 调用,以便有一个工作示例供您查看。
  • 我用 api 调用更新了 stackblitz。未测试,因此您可能需要稍作修改。
  • 我想我已经解决了,只需要先订阅它:)

标签: angular


【解决方案1】:

这可以通过多种方式完成。最好是使用角度输入

import { Component, OnInit, Input } from '@angular/core';

@Component({
 selector: 'app-login',
 templateUrl: './login.component.html',
 styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
@Input() text: string; 
constructor() { }

ngOnInit() {
}

}

然后你可以像这样将变量从父组件传递给子组件

<app-login text="yourvariable or object"></app-login>

【讨论】:

    【解决方案2】:

    我为此目的在我的项目中创建了服务,它将我想要的所有数据保存在对象属性中。然后可以从项目中的任何地方访问它。

    import {Injectable} from '@angular/core';
    
    @Injectable({
      providedIn: 'root'
    })
    export class DataStorage {
      private dataStorage = {};
    
      addData(key: string, data: any) {
        this.dataStorage[key] = data;
      }
    
      getData(key: string) {
        this.changed[key] = false;
        return this.dataStorage[key];
      }
    
      clearData(key: string) {
        this.dataStorage[key] = undefined;
      }
    }
    

    【讨论】:

      【解决方案3】:

      在 App 组件上使用可以从其他组件访问的公共属性不是 Angular 在组件之间共享状态的传统方式,因此我建议不要这样做。

      我会在子组件上使用@Input,以便您可以将对象向下传递给子组件,更多信息在这里:https://angular.io/guide/component-interaction

      或者我会使用带有 BehaviorSubject 的服务,如此处所述https://medium.com/@weswhite/angular-behaviorsubject-service-60485ef064fc

      【讨论】:

        【解决方案4】:

        这可能是最常见、最直接的数据共享方法。当存在父子关系时,它通过使用 @Input() 装饰器来允许通过模板传递数据。您也可以查看@ViewChild 装饰器。 还要查看 EventEmitter。

        在缺少直接连接的组件之间传递数据时,例如兄弟姐妹、孙辈等,您应该使用共享服务。当你有应该同步的数据时,我发现 RxJS BehaviorSubject 在这种情况下非常有用。 参考以下链接:

        https://angularfirebase.com/lessons/sharing-data-between-angular-components-four-methods/

        【讨论】:

          猜你喜欢
          • 2017-06-07
          • 2016-06-25
          • 2021-12-29
          • 2019-11-14
          • 2018-08-20
          • 1970-01-01
          • 2016-06-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多