How to pass object from one component to another in Angular 2?

后端 未结 5 1654
[愿得一人]
[愿得一人] 2020-12-01 06:12

I have Angular components and first component uses the second one as a directive. They should share the same model object, which is initia

5条回答
  •  误落风尘
    2020-12-01 06:28

    From component

    import { Component, OnInit, ViewChild} from '@angular/core';
        import { HttpClient } from '@angular/common/http';
        import { dataService } from "src/app/service/data.service";
        @Component( {
            selector: 'app-sideWidget',
            templateUrl: './sideWidget.html',
            styleUrls: ['./linked-widget.component.css']
        } )
        export class sideWidget{
        TableColumnNames: object[];
        SelectedtableName: string = "patient";
        constructor( private LWTableColumnNames: dataService ) { 
           
        }
        
        ngOnInit() {
            this.http.post( 'getColumns', this.SelectedtableName )
                .subscribe(
                ( data: object[] ) => {
                    this.TableColumnNames = data;
         this.LWTableColumnNames.refLWTableColumnNames = this.TableColumnNames; //this line of code will pass the value through data service
                } );
        
        }    
        }

    DataService

    import { Injectable } from '@angular/core';
    import { BehaviorSubject, Observable } from 'rxjs';
    
    @Injectable()
    export class dataService {
        refLWTableColumnNames: object;//creating an object for the data
    }

    To Component

    import { Component, OnInit } from '@angular/core';
    import { dataService } from "src/app/service/data.service";
    
    @Component( {
        selector: 'app-linked-widget',
        templateUrl: './linked-widget.component.html',
        styleUrls: ['./linked-widget.component.css']
    } )
    export class LinkedWidgetComponent implements OnInit {
    
        constructor(private LWTableColumnNames: dataService) { }
    
        ngOnInit() {
        console.log(this.LWTableColumnNames.refLWTableColumnNames);
        }
        createTable(){
            console.log(this.LWTableColumnNames.refLWTableColumnNames);// calling the object from another component
        }
    
    }

提交回复
热议问题