间隔 Ionic2 或 Angular2 http 请求

Ionic2 or Angular2 http request on interval

我正在尝试创建一个数据服务,每隔设定的秒数从我的 API 和 returns 两个不同数据类型的两个 Observables 中提取数据 API returns。我是 Observables 的新手,所以非常感谢任何帮助。

我的 API returns 两个 json 对象数组(例如 {'Data1':[array of data objects], 'Data2':[array of data objects]})。我可以做类似的事情吗?

@Injectable()
export class DataService {
  data: any = null;
  dataType1: DataType1Model[] = [];
  dataType2: DataType2Model[] = [];
  service: Observable;

  constructor(public http: Http) {}

  start() {
    this.service = Observable.interval(10000)
      .flatMap(() => {
        this.http.get('url')
            .map(res => res.json())
            .subscribe(data => {
              this.data = data;
              this.processData1(this.data.Data1);
              this.processData2(this.data.Data2);
            });
        })
      .subscribe()
  }

  stop(){
    this.service.unsubscribe()
  }

  getData1() {
    return this.dataType1
  }

  getData2() {
    return this.dataType2
  }
}

然后在我的组件中我可以导入 DataService 并调用 data1 = DataService.getData1()?

当 http 请求触发时,该调用将是一个将在 10 秒间隔内继续更新数据的可观察对象吗?同样,我是可观察对象的新手,如果这完全错误,我深表歉意。

您的方法的一个问题是,当您调用 getData1()getData2() 时,无法保证数据已经收到。

我也没看到你在哪里打电话start()

我认为在 this.http.get(...)... 上调用 subscribe(...) 是一个错误。 flatMap() 自己订阅。它期望 Observable 而不是 Subscription,但是当您调用 subscribe() 时,您得到的是 Subscription。要修复它,请将内部 subscribe 替换为 do(并确保导入 do 运算符)或将代码从 subscribe 移动到 map.

您的服务模块将是这样的

@Injectable()
export class DataService {
  constructor(private http : Http) { }

  // Uses http.get() to load a single JSON file
  getData() : Observable<DataType1Model[]> {
      return Observable.interval(10000)
                       .flatMap(this.http.get('url')
                       .map((res:Response) => res.json()));
  }
}

你的组件应该是这样的-

@Component({
  selector: 'Selector',
  template:  "Template",
  providers:[
    DataService,

  ]
})
export class DataComponent implements OnInit{
  dataItem: DataType1Model[]  ;

  constructor(private _itemData:DataService ) { }

  getData(){
    this._itemData.getData()
    .subscribe(
      // the first argument is a function which runs on success
    (data:DataType1Model[]) => {
       this.dataItem = data;
     },
     // the second argument is a function which runs on error
     err => console.error(err),
     // the third argument is a function which runs on completion
     () => console.log('done loading data')

    );
  }

  ngOnInit() {
    console.log('hello `Item` component');
    this.getData();
  }

  stop(){
     _itemData.getData()
    .unsubscribe();
  }
}

取消订阅时请停止。