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

前端 未结 2 1214
逝去的感伤
逝去的感伤 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: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';
    }
    

提交回复
热议问题