isanka thalagala
isanka thalagala

Reputation: 476

Use complex type object In another component in angular 2

I'm new to angular 2 and I'm implementing user sign-In page.If entered email already exist Web API returns user data object. Currently i'm writing that object in console. But I need that object use inside userExist.component.ts.

These 'auth.component.ts' and 'userExist.component.ts' are independent controllers

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

anyone can tell me how should I read object of auth.component.ts inside userExist.component.ts

Upvotes: 0

Views: 42

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222657

You need to use one of the message passing mechanism using shared service/event emitter. In this case since your components are independent, use a shared service.

EXAMPLE

@Injectable()
export class sharedService {
 userRegisterModel:LoggedUserRegister ;
 constructor() {
}
 Initialize() {

}

 saveUser(input:any) {
    this.userRegisterModel = input;
 }

 getUser(){
    return this.userRegisterModel;
 }
}

then inside the AuthComponent

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

again if you want the detail in other component use getUser method

Upvotes: 1

Related Questions