Angular 4 - 仅为2个组件调用一次数据库API

时间:2017-09-12 12:17:59

标签: angular api service router resolve

大师,请帮忙。

  1. service - 使用方法getConfig()从数据库中获取数据并将输出存储在BehaviourSubject observable ConfigArray $

  2. app.component.ts - 首先调用getConfig()并将输出发送到ConfigArray $

  3. status.component.ts - 我使用解析器路由预填充此组件的数据,该组件需要从app.component.ts getConfig()AIP调用获得相同的数据/输出。

  4. 我尝试了不同的方法,比如使用setInterval,promise,observable等待appl.component.ts getConfig()方法完成然后将它传递给status.component.ts解析器路由,但不是那些工作。

    我不确定我在做什么是正确的,有人可以帮助解决这个问题吗?

    谢谢。

    代码:

    感谢Catalyst的快速回复。这是完整的代码:

    config.service.ts

    @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$;
              }
           });
        }
      }
    }
    

    配置-resolver.service.ts

    @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;
          }
        );
      }
    
    }
    

    status.component.ts

    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'];
            }
        );
      }
    
    }
    

0 个答案:

没有答案