将API数据从一个组件传递到另一组件? [英] Pass API data from one component into another component?

查看:99
本文介绍了将API数据从一个组件传递到另一组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Full-stack Angular4,并且想知道如何从一个组件的get调用中获取数据,从而可以使用{{data.name}}将数据中继到html页面中. ?

I am learning Full-stack Angular4, and wanted to know how would I be able to get data from a get call from one component into another so I can relay the data into the html page with {{data.name}}?

我尝试将组件导入另一个组件,然后在该组件中设置一个空对象.da​​ta保存了数据,但是我得到了一个空对象作为响应.

I tried importing the component into the other component, then setting an empty object into that component.data which holds the data, but I get a empty object as a response back.

我在做什么错了?

更新:

我的共享服务:

import {Injectable} from "@angular/core";
import {Http, Response, Headers, RequestOptions} from "@angular/http";
import {Observable} from "rxjs/Rx";
import 'rxjs/add/operator/map';

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

    fetchData() {
        return this.http.get('/api/data').subscribe((data) => {
            this.apiData = data.json();
            console.log(this.apiData);
        })
    }
}

目标组件:

import { Component } from "@angular/core";
import { AllTablesComponent } from '../tables/alltables.component';
import { DataService } from './../data.service';


@Component({
    selector: 'app-target',
    templateUrl: './target.component.html',
    styleUrls: ['./target.component.css']
})
export class TargetComponent {
    data: any;

    constructor(private dataService: DataService) {

        this.data = this.dataService.fetchData();
        console.log("inside target component");
        console.log(this.data);
    }
}

组件中的空对象与数据服务中的实际数据的屏幕截图.

Screenshot of Empty object from component vs actual data from the data service.

推荐答案

首先,您可以看到从后端获取数据之前,已执行控制台登录组件.这是因为这是异步,因此响应需要一些时间才能到达.

First of all, you can see that the console log in component is executed before fetching the data from the backend. This, because this is asynchronous, so it takes a while for the response to arrive.

第二个问题,与同一个问题相关,即这是异步的,即您无法从订阅中返回任何内容,您需要向组件返回一个Observable并在组件中进行订阅,要么手动"完成或使用异步管道.

Second problem, which is related to the same issue, i.e, this being asynchronous, is that you cannot return anything from subscribe, you need to return an Observable to your component and in the component subscribe, either doing it "manually" or then using the async pipe.

如果要在最初获取其他组件后与其他组件共享数据,则可以使用BehaviorSubject,因此请在服务中声明此内容:

If you want to share data to other components after initially getting it another component, what you can do is to use a BehaviorSubject, so declare this in your service:

import {BehaviorSubject} from 'rxjs/BehaviorSubject';

//....

// don't use "any", type your data instead!
private apiData = new BehaviorSubject<any>(null);
public apiData$ = this.apiData.asObservable();

fetchData() {
  return this.http.get('/api/data').map((data) => {
    return data.json();
  })
}

// here we set/change value of the observable
setData(data) { 
  this.apiData.next(data)
}

在要获取数据并要广播到其他组件的组件中,执行...

and in the component where you are fetching the data and want to broadcast to other components, do...

this.dataService.fetchData()
  .subscribe(data => {
    this.data = data;
    // set data in service which is to be shared
    this.dataService.setData(data)
  })

因此,现在我们在此初始组件中获取了数据,并将数据设置为服务中,该数据将广播到所有需要它的其他组件.在这些组件中,您只需订阅此可观察项即可.

So now we have in this initial component fetched the data, and setting the data in service, which is broadcast to all other components that need it. In those components you just subscribe to this observable.

constructor(private dataService: DataService) { 
  dataService.apiData$.subscribe(data => this.data = data)
}

此解决方案基于以下想法:您拥有一个组件,该组件最初会获取数据,然后与其他组件共享.

This solution is based on the idea that you have one component that initially gets the data and then shares it with other components.

这篇关于将API数据从一个组件传递到另一组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆