angular - 使用应用程序组件从角度服务中获取变量
问题描述
我有一个服务,它有一个名为 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
})
})
}
}
我companyDetail
在 app.component 文件中得到:
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
值。
解决方案
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)
})
}
推荐阅读
- reactjs - 将单个 Switch 中的路由拆分为多个组件
- c# - EF Core 包含 Concat 字符串
- javascript - ServiceWorker 如何通过向所有订阅者推送来触发刷新/重新加载?
- postgresql - 如何从 PostgreSQL 的并发事务中从一个表的字段中获取最新的新 id
- javascript - 此代码在哪里返回鼠标位置值?
- flutter - LateInitializationError:使用easy_localization国际化flutter应用程序时,字段'_deviceLocale@66168148'尚未初始化
- javascript - MongooseServerSelectionError: 连接 ECONNREFUSED ::1:27017
- java - 在这个问题中如何避免嵌套的for循环
- java - 如何调用 OAuth 端点以获取在 java 中启用 x509 的 accesstoken?
- python - Python scipy 最小化 - 不产生预期回报的简单示例