【问题标题】:How to pass data from one component to other in angular 2如何以角度2将数据从一个组件传递到另一个组件
【发布时间】:2017-03-15 14:31:52
【问题描述】:

我有我的登录控制器,我可以在其中登录,成功后我会在主页上显示数据。如何将此数据传递给主组件?

这是登录组件中的功能

 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 有我想在主页显示的项目列表。我是 angular 2 的新手。所以我不明白如何访问登录组件中的数据。有没有办法从一个组件访问数据到另一个组件并根据该特定组件处理它?

【问题讨论】:

  • 您也可以使用stackoverflow.com/questions/39738974/…发送数据。
  • 谢谢。我会尝试这种方法。
  • 有很多帖子。您可以使用Input & localStorage 点击链接快乐编码:)
  • 你也可以去Angular website,那里有解决此类常见问题的“秘诀”
  • 是的。我检查了本地存储,但如果第三方 cookie 被阻止,它就不起作用。是否有任何替代本地存储的方法,例如 rootscope 或 angular js 之类的东西?

标签: angular


【解决方案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';
}

【讨论】:

  • 这种方法的问题是我们在页面刷新时丢失了数据
  • 我已经更新了我的答案。您可以使用 localStorage 让您的项目保持刷新。
  • 是的..明白了..只是一个查询。既然可以在任何地方使用本地存储,那么拥有服务有什么用?
  • 它封装了实现细节。如果将来你想实现另一个缓存功能,你需要在一个地方更新你的代码,而不是查看整个项目来找到你使用 localStorage 和“projects_key”常量的所有地方。
  • 为了增加对服务的使用,localStorage中的item在刷新页面之前是不能被其他组件使用的,所以你可以从服务中获取值。
【解决方案2】:

是的,有一种方法可以做到这一点,你可以通过输出装饰器和 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

【讨论】:

    猜你喜欢
    • 2019-08-03
    • 2017-02-15
    • 1970-01-01
    • 2017-05-28
    • 2019-10-27
    • 2021-08-31
    • 2020-12-25
    • 2020-03-28
    相关资源
    最近更新 更多