似乎无法掌握来自服务器的数据填充Observable

时间:2017-07-02 17:18:14

标签: angular angular2-services

我非常精通Angularjs,但我是Angular的新手,我在使用服务调用填充服务器中的observable时遇到了麻烦。

服务很好并且返回我正在寻找的内容,但填充可观察量似乎不起作用。

这是我的组件:

import { Component, OnInit } from '@angular/core';
import { Campaigns } from '../campaigns';
import { CampaignListService } from './campaign-list.service'
import { Subscription, Observable } from 'rxjs';


@Component({
  selector: 'app-campaign-list',
  templateUrl: './campaign-list.component.html',
  styleUrls: ['./campaign-list.component.scss']
})
export class CampaignListComponent implements OnInit {
  campaigns$: Observable<Campaigns[]>;
  subscription: Subscription;

  constructor(private campaignListService:CampaignListService) { }

  ngOnInit() {
   this.campaignListService.getCampaigns().subscribe(campaigns => this.campaigns$ = campaigns);
   console.log(this.campaigns$);
  }

}

这是我的服务:

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

@Injectable()
export class CampaignListService {

  constructor(private _http:Http) { }

  getCampaigns(){
    return this._http.get('http://example.com/api/campaign')
        .map(res => res.json())
  }

}

从我在教程中看到的情况来看,这看起来我应该能够控制日志活动$ observable,但我得到了一个未定义的。

任何见解都会非常感激!

1 个答案:

答案 0 :(得分:1)

该行

this.campaignListService.getCampaigns().subscribe(data => this.campaigns$);

应该是

this.campaigns$ = this.campaignListService.getCampaigns();

您的服务返回Observable<Campaigns[]>(尽管它没有将其指定为返回值,但应该),并且您只想将Observable存储在组件中。

如果您想要存储广告系列数组,发布由您的组件中的observable发布,那么您必须订阅并执行

this.campaignListService.getCampaigns().subscribe(campaigns => this.campaigns = campaigns);