typescript 以角度将数据从一个组件传递到另一个组件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/55125640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:48:42  来源:igfitidea点击:

Pass data from one component to another in angular

javascriptarraysangulartypescriptcomponents

提问by KshitijAnil Rangari

I am working on a application which contains a search functionality.

我正在开发一个包含搜索功能的应用程序。

Right now I have 2 components in application 1. Navbar 2. SearchGridList

现在我在应用程序 1. Navbar 2. SearchGridList 中有 2 个组件

Navbar component contains a text box, in which you type in a search query and hit enter and this component will make a api call and get the data. When the data comes back, I want to populate this data in an array in SearchGridList component.

Navbar 组件包含一个文本框,您可以在其中输入搜索查询并按 Enter,该组件将进行 api 调用并获取数据。当数据回来时,我想将此数据填充到 SearchGridList 组件中的数组中。

I am having a tough time understanding passing data within components in Angular, can someone please take a look at my code and guide me.

我很难理解在 Angular 中的组件内传递数据,有人可以看看我的代码并指导我。

navbar.component.ts

导航栏.component.ts

import { Component, OnInit, Input, Output } from '@angular/core';
import {DataService} from '../../services/data.service';
import {SearchResults} from '../class/search.class';
import {SearchGridListComponent} from '../search-grid-list/search-grid-list.component';
import { EventEmitter } from '@angular/core';

@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {

  searchQuery : String;
  //searchResultList : Array<any> = [];

  constructor(private dataService :  DataService) { }

  doSearch () : any
  {
    this.dataService.doSQLSearch(this.searchQuery)
    .then ((data:any)=>{
      for (var i =0; i<data.Results.length;i++){
        let searchObj = new SearchResults(data.Results[i]);
        //I want to push data into array from SearchGrid like this 
        resultGridList.push(searchObj);

      }
    });
   }

  ngOnInit() {
  }
}

navbar.component.html

导航栏.component.html

<mat-toolbar class="main-header">
  <a href="/">
  <img src="../../../assets/vms-header-logo.png" id= "header-logo">
  </a>
    <form class="search-box">
      <mat-form-field  class="search-box-full-width">
        <input id ="search-textbox" matInput placeholder="Enter a Barcode, DSID or any search term" name="Search" [(ngModel)]="searchQuery" (keyup.enter)="doSearch()" autocomplete="off">
      </mat-form-field>
    </form>
</mat-toolbar>

search-grid.component.ts

搜索grid.component.ts

import { Component, OnInit, Input } from '@angular/core';
import {NavbarComponent} from '../navbar/navbar.component';

@Component({
  selector: 'app-search-grid-list',
  templateUrl: './search-grid-list.component.html',
  styleUrls: ['./search-grid-list.component.css'],
})
export class SearchGridListComponent implements OnInit {
  resultGridList : Array <any> = [];
  constructor() { }

  ngOnInit() {
  }

}

采纳答案by Kamil Kie?czewski

You need to add to navbar following @Outputevent:

您需要添加到导航栏以下@Output事件:

export class NavbarComponent implements OnInit {
   ...
   @Output() public found = new EventEmitter<any>();
   ...
   doSearch () : any
   {
    this.dataService.doSQLSearch(this.searchQuery) .then ((data:any)=>{
      for (var i =0; i<data.Results.length;i++){
        let searchObj = new SearchResults(data.Results[i]);

        this.found.emit(searchObj);  // !!!! here emit event
                                     // however emitting events in loop looks strange... better is to emit one evet

      }
    });
   }
   ...
}

Ok in your grid component use @Inputas resultGridListparameter

好的,在您的网格组件中@Input用作resultGridList参数

export class SearchGridListComponent implements OnInit {

  @Input() public resultGridList : Array <any> = [];
  ...
}

Ok and now in your App component join this two in following way

好的,现在在您的 App 组件中按以下方式加入这两个

App template html:

应用模板html:

<app-navbar (found)="handleResults($event)"></app-navbar>

<app-search-grid-list [resultGridList]="data"></app-search-grid-list>

And in App ts file:

在 App ts 文件中:

data = [];
...

handleResults(searchObj) {
  this.data = searchObj
}

回答by Hien Nguyen

You can create a BehaviorSubjectin your DataService

你可以BehaviorSubject在你的DataService

private messageSource = new BehaviorSubject<string>('service');

You can refer this demo for passing data between component.

您可以参考此演示在组件之间传递数据。

https://stackblitz.com/edit/behavior-subject-2019

https://stackblitz.com/edit/behavior-subject-2019

回答by Jeremy Thille

Simply inject dataServicein search-gridcomponent as well. Services are singletons, you can share them across components.

只要注入dataServicesearch-grid组成部分,也是。服务是单例的,你可以跨组件共享它们。

In one component :

在一个组件中:

dataService.test = "hello";

in another component :

在另一个组件中:

console.log(dataService.test); // "hello"

That's what services are for.

这就是服务的用途。