【问题标题】:Use complex type object In another component in angular 2在角度2的另一个组件中使用复杂类型对象
【发布时间】:2018-01-13 10:38:53
【问题描述】:

我是 Angular 2 的新手,我正在实现用户登录页面。如果输入的电子邮件已经存在,Web API 返回用户数据对象。目前我正在控制台中编写该对象。但我需要在 userExist.component.ts 中使用该对象。

这些 'auth.component.ts' 和 'userExist.component.ts' 是独立的控制器

auth.component .ts

export class AuthComponent implements OnInit {

 ( ......)
   
 userRegister() {
   
   ( ......)
    
   this.userService.loginRegisterUser(this.userRegisterModel)
      .subscribe(
      data =>{ 
        console.log(data); // working!!   
        this.router.navigateByUrl('/user-exist');   
      },     
      err => {
        alert(err);
        this.errors = err;
        this.isRegistering = false;
      }
      );
   }
}

userExist.component.ts

export class UserExistComponent implements OnInit {

  userRegisterModel:LoggedUserRegister = new LoggedUserRegister ();

  constructor(private route: ActivatedRoute, private router: Router, private userService: UserService,  private fb: FormBuilder,) {}
  
  ngOnInit() {
    this. userRegisterModel = // I need assign object from auth.component.ts
  }
}

任何人都可以告诉我应该如何在 userExist.component.ts 中读取 auth.component.ts 的对象

【问题讨论】:

    标签: javascript angular angular2-routing


    【解决方案1】:

    您需要使用其中一种使用共享服务/事件发射器的消息传递机制。在这种情况下,由于您的组件是独立的,请使用 shared service.

    示例

    @Injectable()
    export class sharedService {
     userRegisterModel:LoggedUserRegister ;
     constructor() {
    }
     Initialize() {
    
    }
    
     saveUser(input:any) {
        this.userRegisterModel = input;
     }
    
     getUser(){
        return this.userRegisterModel;
     }
    }
    

    然后在AuthComponent

    里面
    data =>{ 
            this.sharedService.saveUser(data);
            this.router.navigateByUrl('/user-exist');   
    }
    

    如果您想了解其他组件中的详细信息,请再次使用 getUser 方法

    【讨论】:

    • 是的,它奏效了。这是非常容易使用的方法。这对像我这样的初学者非常有帮助:) 谢谢#Sajeetharan
    • @isankathalagala 随时:)
    猜你喜欢
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 2018-06-07
    • 2018-04-24
    • 2018-02-25
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    相关资源
    最近更新 更多