How to pass data from one component to other in angular 2

前端 未结 2 1215
逝去的感伤
逝去的感伤 2020-12-20 06:22

I have my login controller where i login and on success I get data to be displayed on home page. How do i pass this data to home component?

this is the function in l

相关标签:
2条回答
  • 2020-12-20 06:29

    Yes, theres a way to do it,and you do this through the Output decorator and EventEmmiter class (both from angular/core). For example, in one of my projects I use select2 for Angular, wich tells me the actual selected value through the output "valueChanged", then I made a "event handler" wich will be executed everytime "valueChanged" event is executed. This event handler is also an output event itself, and will be executed just after valueChanged, and I do this to pass data to the parent component. You can repeat this approach all the times you need. Here is my code

    ts:

    import { Output, EventEmitter, Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'app-select2item',
      templateUrl: './select2item.component.html',
      styleUrls: ['./select2item.component.css']
    })
    export class Select2itemComponent implements OnInit {
    
        private select2options:S2options;
      private selected:string;
      @Output()//this is how you declare a custom "output event"
      selectedItem = new EventEmitter();
      constructor() { }
    
      ngOnInit() {
        this.select2options = {};
        this.select2options.ajax={
            url:"/item/ajax",
            dataType: 'json',
            data: (term)=>{ //console.log(term.term);
            return {sku:term.term}; 
          },
            delay:1000,
            processResults: (data)=>{
                console.log(data);
                return {
                    results:data.map((item)=>{
                        return {id:item.id, text:item.name};
                    })
                }
            }
        };
    
      }
    //and this is where you define your custom "output event"
      public currentItem(e:any){
        this.selected=e.value;
        this.selectedItem.emit(this.selected);
      }
    
    }
    

    html:

    <select2 [options]="select2options" 
    (valueChanged)="currentItem($event)"></select2>
    

    take a look to this quick tutorial, it will help you (its made by Ionic team):

    Angular Outputs

    0 讨论(0)
  • 2020-12-20 06:35

    It's better to use services to share data between components. You can create something like following

    // replace any to your actual projects type
    @Injectable()
    export class ProjectsService {
        public setProjects(projects: any) {
            this._projects = projects;
        }
    
        public get projects(): any {
            return this._projects;
        }
    
        private _projects: any = null; //or empty array if projects is an array
    }
    

    Then you can inject it in both Login and Home components:

    export class LoginComponent {
        constructor(private projectsService: ProjectsService) { }
    
        ngOnInit() {
          this.returnUrl = '/home';
          }
    
          doLogin(event) {
           // console.log(event);
           // console.log(this.loginForm.value);
           this.authenticationService.login(this.loginForm.value.username, this.loginForm.value.password)
           .subscribe(
           (response) => {
            console.log(response);
           if(response.authenticateResult==0){
            sessionStorage.setItem('user_token', response.user_token);
           console.log(response.project_list.projects);
            this.projectsService.setProjects(response.project_list.projects);
            this.router.navigate([this.returnUrl]);
            }else{
        this.error = 'Please enter correct Username and password';
            }
           }
           )
          }
    }
    
    export class HomeComponent {
        constructor(private projectsService: ProjectsService) { }
    
        ngOnInit() {
          console.log(this.projectsService.projects);
        }
    }
    

    Update:

    You can additionally save tour projects in LocalStorage:

    // replace any to your actual projects type
    @Injectable()
    export class ProjectsService {
        constructor() {
            const projects: any = localStorage.getItem(this.projectsKey);
            if (projects) {
                this._projects = JSON.parse(projects);
            }
        }
        public setProjects(projects: any) {
            localStorage.setItem(this.projectsKey, JSON.stringify(projects));
            this._projects = projects;
        }
    
        public get projects(): any {
            return this._projects;
        }
    
        private _projects: any = null; //or empty array if projects is an array
        private readonly projectsKey: string = 'projects_key';
    }
    
    0 讨论(0)
提交回复
热议问题