简体   繁体   中英

Variable sharing between two sibling component in angular 4?

I have 2 sibling component and I want to access one variable of one component to be accessed in another one. I used shared Services but it is not working. Can you please tell where am I wrong?

Service:

@Injectable()
export class SharedService{
  private isSuccess = new Subject<boolean>();
  getSaveBtnStatus(){
    return this.isSuccess.asObservable();
  }
  setSaveBtnStatus(value: boolean){
    this.isSuccess.next(value);
  }
}

Component 1:

@Injectable()
export class LoginComponent implements OnInit {
  constructor(private http: Http, private route: ActivatedRoute, private router: Router, private myshared: SharedService) {
  }

  ngOnInit() {    
  }

  login = (user) => {
    var username = user.username;
    var password = user.password;
    var user_api , user_birth ;
    var url = 'https://swapi.co/api/people/?search='+username;
    this.http.get(url).subscribe(data => { 
      var count = data.json().count;
      if( count == 0 )alert("NO such user");
    if( count > 0 ) {
      user_api= (data.json().results[0].name);
      user_birth = (data).json().results[0].birth_year;
      if( password == user_birth && username == user_api ) {
        console.log("Successful");
        this.myshared.setSaveBtnStatus(true);// using shared service
        this.router.navigate(['/search']);
     } else if ( password != user_birth || username != user_api) 
       alert("CHECK Your Username and Passowrd");
   }
  })
  }
}

Component 2:

export class SearchPlanetComponent implements OnInit {
  form;
  private loading: boolean = false;
  private results: Observable<Array<String>>;
  public searchField : FormControl
  private isSuccess :Boolean
  constructor(private myservice: SearchService,
    private myshared:SharedService, private http: Http) {
  }
  ngOnInit() {
    this.myshared.getSaveBtnStatus().
      subscribe(
        data => console.log(data) // nothing is printed in console.
      );
}

please tell why the service function get/set is not working?

It doesn't work because when you emit value inside subject the underlying component was suppose to listen wasn't loaded. That component is getting loaded after router.navigate called.

You should consider using BehaviorSubject instead of Subject , as BehaviourSubject persist last emitted value. Also it emits last/inital persisted value when someone subscribes to it.

//it needs initial state while registering it, so passed false
private isSuccess = new BehaviorSubject<boolean>(false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM