简体   繁体   中英

Get variable from angular service with the app component

I have a service that has a public property called companyDetail, And in the constructor, I set its value from the native storage:

import { Platform } from '@ionic/angular';
import { Injectable } from "@angular/core";
import { NativeStorage } from '@ionic-native/native-storage/ngx';

@Injectable({
    providedIn: 'root'
})
export class SharedDataService{
    public companyDetail;
    constructor( private platform:Platform, private nativeStorage: NativeStorage ){
        this.platform.ready().then(()=>{
            this.nativeStorage.getItem('company').then(res=>{
                this.companyDetail = res
            })
    })
    }
}

I get the companyDetail in the app.component file:

import { Platform } from '@ionic/angular';
import { NativeStorage } from '@ionic-native/native-storage/ngx';
import { SharedDataService } from './content/services/sharedData.service';
import { Component } from '@angular/core';
@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.scss']
})
export class AppComponent {
    constructor(private sharedData:SharedDataService ){
         console.log(this.sharedData.companyDetail);
    }
}

But it is always logging null value.

I think you have async problem,

I am not familiar with Ionic, this is the simple example for web.

If you can use Rxjs in your Ionic project this example should work for Ionic too.

import { Platform } from '@ionic/angular';
import { Injectable } from "@angular/core";
import { NativeStorage } from '@ionic-native/native-storage/ngx';
import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject';

@Injectable({
    providedIn: 'root'
})
export class SharedDataService{
    public companyDetail = null;
    public companyDetailSubject = new BehaviorSubject(this.companyDetail);

    constructor( private platform:Platform, private nativeStorage: NativeStorage ){
        this.platform.ready().then(()=>{
            this.nativeStorage.getItem('company').then(res=>{
                this.companyDetail = res;
                this.companyDetailSubject.next(this.companyDetail);
            })
    })
    }
}

and in app.component.ts

imports

import { filter, take } from 'rxjs/operators';

constructor

   constructor(private sharedData:SharedDataService ){
      this.sharedData.companyDetailSubject.pipe(
          filter(value => !!value), 
          take(1)
      ).subscribe(response => {
           console.log(response)
      })
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM