在角度组件之间共享字符串

时间:2019-02-10 02:05:55

标签: angular typescript firebase

我试图能够访问Firebase数据库以获取存储的设置,然后在AppComponent中设置这些变量,然后能够从与导入AppComponent的任何其他组件中检索该字符串。

我在AppComponent中有此设置(它检索设置并将其单独和成组设置。让我们以company作为我们要共享的变量。

export class AppComponent {
    public company: string;
    public title: string;
    public version: string;
    public show: boolean = false;
    public settings: Observable<any>;

    constructor(private dropConfig: NgbDropdownConfig, private router: Router, private db: AngularFireDatabase, public authService: AuthService, private afAuth: AngularFireAuth) {
        afAuth.authState.subscribe(user => {
            if(user) {
                this.authService.findCompany().then((resp) => {
                    this.db.object(resp['company']+'/settings/users/'+user.uid+'/').valueChanges().subscribe((user) => {
                        this.company = resp['company'];
                        dropConfig.placement = 'bottom-right';
                        this.settings = db.object(this.company+'/settings/general').valueChanges();
                        this.settings.subscribe((setting) => {
                            this.title = setting.title;
                            this.version = setting.version;
                            this.show = true;
                        });
                    })
                });
            } else {
                this.show = false;
            }
        });
    }

    ngOnInit() {

    }
}

例如,在我的导航栏组件中,我尝试导入AppComponent,然后console.log退出公司字符串。

如果我将其放置在构造函数中:

constructor(public appComp: AppComponent) {
    console.log(this.appComp)
}

这就是我在控制台中得到的:(简而言之,为了简单起见)

AppComponent {company: "acme-industries"}

现在,如果我将console.log更改为以下内容:

console.log(this.appComp.company)

这就是我在控制台中看到的。

undefined

接收此信息的正确方法是什么?当我将其保留在appComp时可用,但是一旦我尝试进入数组,似乎所有信息都消失了。

更新

根据下面的评论,我创建了一个服务(力所能及),该服务将所有这些设置放在对象中,然后尝试返回该对象。服务如下。

import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { AuthService } from '../auth/auth.service';
import { AngularFireDatabase, AngularFireObject } from '@angular/fire/database';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs';
import { tap, delay, map, first } from 'rxjs/operators';

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

    public sets: Observable<any>;
    public settings = {
        "show" : false,
        "company" : null,
        "title" : null,
        "version" : null
    }

    constructor(private authService: AuthService, private afAuth: AngularFireAuth, private db: AngularFireDatabase) {
        this.afAuth.authState.subscribe(user => {
            if(user) {
                this.authService.findCompany().then((resp) => {
                    this.sets = this.db.object(resp["company"]+'/settings/general').valueChanges();
                    this.sets.subscribe((response) => {
                        this.settings.show = true;
                        this.settings.company = resp["company"];
                        this.settings.title = response["title"];
                        this.settings.version = response["version"];
                    });
                });
            }
        });
    }
}

更新

根据上面的更新,这是要匹配的app.component

import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { AngularFireAuth } from '@angular/fire/auth';
import { AuthService } from './auth/auth.service';
import { DefaultsService } from './defaults/defaults.service';
import { Observable } from 'rxjs';
import { NgbDropdownConfig } from '@ng-bootstrap/ng-bootstrap';
import { filter, distinctUntilChanged, map, subscribeOn } from 'rxjs/operators';
import { ActivatedRoute, Router, NavigationStart, NavigationEnd, PRIMARY_OUTLET } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    title: string;
    version: string;
    show: boolean;

    constructor(private dfServices: DefaultsService, private dropConfig: NgbDropdownConfig, private router: Router, db: AngularFireDatabase, public authService: AuthService, private afAuth: AngularFireAuth) {
        afAuth.authState.subscribe(user => {
            if(user) {
                console.log(dfServices.settings);
                this.show = dfServices.settings.show;
                this.title = dfServices.settings.title;
                this.version = dfServices.settings.version
            }
        });
    }

    ngOnInit() {
    }
}

2 个答案:

答案 0 :(得分:2)

这是一项针对角度服务的工作。您应该通过公共服务组件公开共享的数据,应用程序组件和导航栏组件都使用注入来共享这些数据。

答案 1 :(得分:1)

import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { AngularFireAuth } from '@angular/fire/auth';
import { AuthService } from './auth/auth.service';
import { DefaultsService } from './defaults/defaults.service';
import { Observable } from 'rxjs';
import { NgbDropdownConfig } from '@ng-bootstrap/ng-bootstrap';
import { filter, distinctUntilChanged, map, subscribeOn } from 'rxjs/operators';
import { ActivatedRoute, Router, NavigationStart, NavigationEnd, PRIMARY_OUTLET } from '@angular/router';

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

    public sets: Observable<any>;

    title: string;
    version: string;
    show: boolean;

    constructor(private dfServices: DefaultsService, private dropConfig: NgbDropdownConfig, 
      private router: Router, db: AngularFireDatabase, public authService: AuthService, 
      private afAuth: AngularFireAuth) {

        afAuth.authState.subscribe(user => {
          if(user) {
              this.authService.findCompany().then((resp) => {
                  this.sets = db.object(resp["company"]+'/settings/general').valueChanges();
                  this.sets.subscribe((response) => {
                      dfServices.settings = {
                        "show" : true,
                        "company" : resp["company"],
                        "title" : response["title"],
                        "version" : response["version"]
                    };
                  });
              });
          }
        });
    }

    ngOnInit() {
    }
}

您的DefaultsService应该是


import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { AuthService } from '../auth/auth.service';
import { AngularFireDatabase, AngularFireObject } from '@angular/fire/database';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs';
import { tap, delay, map, first } from 'rxjs/operators';

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

    public sets: Observable<any>;
    public settings = {
        "show" : false,
        "company" : null,
        "title" : null,
        "version" : null
    }

    constructor(private authService: AuthService, private afAuth: AngularFireAuth, private db: AngularFireDatabase) {
    }

    getSettings() {
      return this.settings;
    }
}

然后,您可以将DefaultsService注入其他组件并调用getSettings。当然,还有其他更清洁的方法可以实现这一目标,如果您愿意,我可以发布更好的解决方案。

更新


import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { AuthService } from '../auth/auth.service';
import { AngularFireDatabase, AngularFireObject } from '@angular/fire/database';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs';
import { tap, delay, map, first } from 'rxjs/operators';

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

  public sets: Observable<any>;

  private settingsObs = null;

  constructor(private authService: AuthService, private afAuth: AngularFireAuth, private db: AngularFireDatabase) {
    this.createSettingsObs();
  }

  getSettings() {
    return this.settingsObs;
  }

  createSettingsObs() {

    this.settingsObs = Observable.create(function (observer) {

      this.afAuth.authState.subscribe(user => {
        if (user) {
          this.authService.findCompany().then((resp) => {
            this.sets = this.db.object(resp["company"] + '/settings/general').valueChanges();
            this.sets.subscribe((response) => {
              const settings = {
                "show": true,
                "company": resp["company"],
                "title": response["title"],
                "version": response["version"]
              };
              observer.next(settings);
            });
          });
        }
      });
    });
  }
}

在任何组件中,您都应订阅,因为您不知道对服务器的呼叫实际上何时会结束:

import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';
import { AngularFireAuth } from '@angular/fire/auth';
import { AuthService } from './auth/auth.service';
import { DefaultsService } from './defaults/defaults.service';
import { Observable } from 'rxjs';
import { NgbDropdownConfig } from '@ng-bootstrap/ng-bootstrap';
import { filter, distinctUntilChanged, map, subscribeOn } from 'rxjs/operators';
import { ActivatedRoute, Router, NavigationStart, NavigationEnd, PRIMARY_OUTLET } from '@angular/router';

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

  public sets: Observable<any>;

  title: string;
  version: string;
  show: boolean;

  constructor(private dfServices: DefaultsService, private dropConfig: NgbDropdownConfig,
    private router: Router, db: AngularFireDatabase, public authService: AuthService,
    private afAuth: AngularFireAuth) {
  }


  ngOnInit() {
    this.dfServices.getSettings.subscribe((settings: any)=> {
      console.log(settings);
    });
  }
}