0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yes it worked. It's very easy method to use.this will very helpful to beginners like me :) Thank you #Sajeetharan
@isankathalagala any time :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.