我是 Angular 2 的新手,正在实现用户登录页面。如果输入的电子邮件已存在,Web API 将返回用户数据对象。目前我正在控制台中编写该对象。但我需要在 userExist.component.ts 中使用该对象。
这些“auth.component.ts”和“userExist.component.ts”是独立的 Controller
auth.组件.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 对象
最佳答案
您需要使用一种使用共享服务/事件发射器的消息传递机制。在这种情况下,由于您的组件是独立的,因此请使用共享服务。
示例
@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
方法
关于javascript - 在 Angular 2 的另一个组件中使用复杂类型对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48239063/