【问题标题】:pass a data from angular 2 service that uses http to a component将使用 http 的 Angular 2 服务中的数据传递给组件
【发布时间】:2016-12-24 23:02:18
【问题描述】:

我有一个从服务调用函数的组件。

    export class ZoomComponent { 
    constructor(private productService: ProductService){}
     container: any;
     product:ProductObj[];
    ngOnInit() {
      this.product = this.productService.getProduct()
    }
 }

在服务中,我有一个带有 subscribe 的 http 调用。我希望将 http 请求的结果重新调整到我的组件。

@Injectable()
export class ProductService {   

    product:ProductObj[];
    constructor(private http: Http) { }

     getProduct() {         
        return this.http.get('./friends.json').map((res:Response) => res.json()) .subscribe(
                data => this.product = data
                //function(data){console.log(data)}
            )       
        }   
}

我是 angular2 的新手。我希望作为对我的组件的 http 请求的结果返回产品变量。但是在给出一个 console.log 时,可观察对象返回时没有我的响应数据

【问题讨论】:

标签: http angular


【解决方案1】:
@Injectable()
export class ProductService {   
    constructor(private http: Http) { }

    getProduct() {         
       return this.http.get('./friends.json')
         .map((res:Response) => res.json())     
    }   
}

在组件中:

constructor( private productService: ProductService) {}

ngOnInit() {
    this.productService.getProduct().subscribe(
       data => console.log(data)
    )
}

【讨论】:

  • 没问题!不要忘记将此标记为答案;)
  • @stijn.aerts 如果我们订阅服务怎么办?我们如何返回组件中的数据?
猜你喜欢
  • 1970-01-01
  • 2019-05-26
  • 1970-01-01
  • 2018-03-29
  • 2017-08-30
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
  • 2017-05-25
相关资源
最近更新 更多