大师,请帮忙。
service - 使用方法getConfig()从数据库中获取数据并将输出存储在BehaviourSubject observable ConfigArray $
app.component.ts - 首先调用getConfig()并将输出发送到ConfigArray $
status.component.ts - 我使用解析器路由预填充此组件的数据,该组件需要从app.component.ts getConfig()AIP调用获得相同的数据/输出。
我尝试了不同的方法,比如使用setInterval,promise,observable等待appl.component.ts getConfig()方法完成然后将它传递给status.component.ts解析器路由,但不是那些工作。
我不确定我在做什么是正确的,有人可以帮助解决这个问题吗?
谢谢。
代码:
感谢Catalyst的快速回复。这是完整的代码:
@Injectable()
export class ConfigService {
private configsArray = new BehaviorSubject<Config>(undefined);
configsArray$ = this.configsArray.asObservable().first();
updateConfigs(configs: Config) {
this.configsArray.next(configs)
}
getConfigs() {
let initialLoad: number = 0;
let initialLoadDone: boolean = false;
if (this.fetchConfigs) == 'NotFetched') {
// if it meets this if condition it is working
let headers = new Headers();
headers.append('Content-Type','application/json');
this.updateFetchConfigs('Fetching');
return this.http.get('http://localhost:8080/sample1/api/config', { headers: headers }).map((response: Response) => response.json());
}
else {
// if it does not meet this if condition it is not working
Observable.interval(1)
.takeWhile(() => !initialLoadDone)
.subscribe(() => {
++initialLoad;
if (this.getConfigs1(this.fetchConfigs$) == 'Fetched' || initialLoad > 10000) {
initialLoadDone = true;
return this.configsArray$;
}
});
}
}
}
@Injectable()
export class ConfigResolver implements Resolve<Config> {
config: Config;
constructor(private configService: ConfigService, private router:Router) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Config> | Promise<Config> | Config {
return this.configService.getConfigs().map(
data => {
return data;
}
);
}
}
export class StatusComponent implements OnInit, OnDestroy {
constructor(private configService:ConfigService,
private route: ActivatedRoute,
private router: Router) {}
ngOnInit() {
this.configSubscription = this.route.data.subscribe(
(data: Data) => {
this.test = data['config'];
}
);
}
}