如何以角度2

时间:2017-03-15 05:13:04

标签: angular

我有登录控制器,我登录并成功获取数据显示在主页上。如何将此数据传递给home组件?

这是登录组件

中的功能
 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包含我想在主页中显示的项目列表。我是角度2的新手。所以我不明白我如何访问登录组件中的数据。有没有办法从1个组件访问其他组件并根据该特定组件处理它?<​​/ p>

2 个答案:

答案 0 :(得分:1)

最好使用services在组件之间共享数据。您可以创建类似下面的内容

// 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
}

然后你可以在Login和Home组件中注入它:

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);
    }
}

<强>更新

您还可以在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';
}

答案 1 :(得分:0)

是的,这是一种方法,你可以通过Output装饰器和EventEmmiter类(来自angular / core)来实现。 例如,在我的一个项目中,我使用select2作为Angular,通过输出“valueChanged”告诉我实际选择的值,然后我做了一个“事件处理程序”,每次执行“valueChanged”事件时都会执行。此事件处理程序本身也是一个输出事件,将在valueChanged之后执行,我这样做是为了将数据传递给父组件。您可以随时重复此方法。这是我的代码

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>

看看这个快速教程,它会帮助你(由Ionic团队制作):

Angular Outputs