1

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 login Component

 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.router.navigate([this.returnUrl]);
    }else{
this.error = 'Please enter correct Username and password';
    }
   }
   )
  }

response.project_list.projects has list of projects which I want to display in home page. I am new to angular 2 . So I am not understanding how i can get access to the data which is in login component. Is there any way to access data from 1 component to other and process it according to that particular component?

Naik Ashwini
  • 750
  • 12
  • 32
  • 1
    You can use http://stackoverflow.com/questions/39738974/can-i-emmit-the-event-from-parent-to-child-in-angular2 to send data also. – ranakrunal9 Mar 15 '17 at 05:14
  • Thank you. I will try this approach. – Naik Ashwini Mar 15 '17 at 05:22
  • There are a lot of posts. You can use [**Input**](http://stackoverflow.com/questions/42320402/input-not-working-in-angular-2/42320582#42320582) & [**localStorage**](http://stackoverflow.com/questions/42603319/how-to-store-an-object-of-a-class-type-in-browsers-storage-and-retrieve-it/42603514#42603514) click on the links Happy coding :) – Aravind Mar 15 '17 at 05:24
  • You can also go to the [Angular website](https://angular.io) where they have "recipes" for tackling common problems like this – Gab Mar 15 '17 at 05:27
  • Yeah. I checked local storage, but in case there third part cookies are blocked it doesn't work. Is there any alternate for local storage like rootscope or something like in angular js? – Naik Ashwini Mar 15 '17 at 05:27
  • @MendonAshwini asking me ? something? – Aravind Mar 15 '17 at 05:43
  • @Aravind yes. About local storage. As i find using local storage may create problem in case third party cookies are blocked – Naik Ashwini Mar 15 '17 at 05:48
  • yeah . I think sharing data with Service will solve the localstorage problem too – Naik Ashwini Mar 15 '17 at 06:07

2 Answers2

1

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';
}
Sergey Mozhaykin
  • 192
  • 1
  • 10
  • Problem with this approach is we loose the data on page refresh – Naik Ashwini Mar 15 '17 at 06:26
  • I've updated my answer. You can use localStorage to keep your projects between refresh. – Sergey Mozhaykin Mar 15 '17 at 06:32
  • yeah.. got it.. just a query. Now that localstorage can be used from anywhere, whats the use of having a service? – Naik Ashwini Mar 15 '17 at 06:40
  • 1
    It encapsulates implementation details. If in future you want to implement another caching functionality you need to update your code in one place instead of looking through entire project to find all the places where you're using localStorage and 'projects_key' constant. – Sergey Mozhaykin Mar 15 '17 at 06:45
  • To add to the use of service, item in localStorage won't be available for another component until you refresh the page, so you can get the value from the service instead. – piritocle Apr 07 '21 at 13:05
0

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

Gustavo Topete
  • 1,246
  • 1
  • 9
  • 15