我有一个服务,该服务具有一个名为companyDetail的公共属性,并且在构造函数中,我从本地存储中设置了它的值:
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
})
})
}
}
我在app.component文件中获得了companyDetail
:
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);
}
}
但是它总是记录null
值。
我认为您有异步问题,
我不熟悉Ionic,这是网络的简单示例。
如果您可以在Ionic项目中使用Rxjs,则此示例也适用于Ionic。
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);
})
})
}
}
和在app.component.ts中
进口
import { filter, take } from 'rxjs/operators';
构造函数
constructor(private sharedData:SharedDataService ){
this.sharedData.companyDetailSubject.pipe(
filter(value => !!value),
take(1)
).subscribe(response => {
console.log(response)
})
}