外部订阅无法访问角度数据

时间:2018-01-07 23:24:51

标签: angular typescript angular2-routing

我有一个关于Angular 2的问题(抱歉我的英语不够好......)。

我想操纵其他组件的组件变量。问题是这个组件变量在 subscribe 函数之外未定义,而在内部清晰可见。所以,如果没有这个组件,我不能指望访问这个变量。

这是我的服务 MailRepertoryService

    import { Injectable } from '@angular/core';
    import { Http } from '@angular/http';
    import 'rxjs/add/operator/map';

    @Injectable()
    export class MailRepertoryService {

      constructor(private http: Http) { }

      getMailsRepertory() {
        return this.http
          .get('data/dossiers.json')
          .map(res => res.json());
      }

      getMailsRepertoryFields() {
        return this.http
          .get('data/champs.json')
          .map(res => res.json())
      }

    }

这是我的 AppComponent

    import { Component, Input } from '@angular/core';
    import { MailRepertoryService } from './services/mail.repertory.service';
    import { Box, Field, Mail } from './types/mailbox.type';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })

    export class AppComponent {

      private title = 'Em Ta Box';
      boxRepertory: Box[];
      mailRepertory: Box;
      fields: Field[];
      private errors: string;

      constructor(private mailRepertoryService: MailRepertoryService) {}

      ngOnInit() {
        this.mailRepertoryService.getMailsRepertory().subscribe(
          (mailRepertories: Box[]) => {
            this.boxRepertory = mailRepertories;
            console.log(this.boxRepertory); // visible object
          },
          error => {
            console.error(error);
            this.errors = error;
          }
        );
        this.mailRepertoryService.getMailsRepertoryFields().subscribe(
          data => this.fields = data,
          error => {
            console.error(error);
            this.errors = error;
          }
        );
        console.log(this.boxRepertory); // undefined
      }

    }

如何在订阅之外访问 this.boxRepertory 变量?

谢谢。

1 个答案:

答案 0 :(得分:0)

试试这个。从rxjs导入Observable以使用flatMap

ngOnInit() {
    this.mailRepertoryService.getMailsRepertory().flatMap(
      (mailRepertories: Box[]) => {
        this.boxRepertory = mailRepertories;
        console.log(this.boxRepertory); // visible object
        return this.mailRepertoryService.getMailsRepertoryFields();
 }).subscribe(
      data => this.fields = data,
      (error) => {
        console.error(error);
        this.errors = error;
      }, 
      () => {
        console.log(this.boxRepertory);
      });
   }