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

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

问题描述

我正在学习全栈 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}}?

我尝试将组件导入另一个组件,然后将一个空对象设置到包含数据的 component.data 中,但我得到一个空对象作为响应.

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)
  })

所以现在我们已经在这个初始组件中获取了数据,并设置了服务中的数据,这会广播给所有其他需要它的组件.在这些组件中,您只需订阅这个 observable.

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天全站免登陆