我有2个兄弟组件,我想访问另一个组件中要访问的一个组件的一个变量。我使用共享服务,但它不起作用。你能告诉我哪里错了吗?
服务:
@Injectable()
export class SharedService{
private isSuccess = new Subject<boolean>();
getSaveBtnStatus(){
return this.isSuccess.asObservable();
}
setSaveBtnStatus(value: boolean){
this.isSuccess.next(value);
}
}
组件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");
}
})
}
}
组件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.
);
}
请说明为什么服务功能获取/设置不起作用?
答案 0 :(得分:0)
它不起作用,因为当你在主题内发出值时,底层组件被认为是没有加载的。调用router.navigate
后,该组件将被加载。
您应该考虑使用BehaviorSubject
代替Subject
,因为BehaviourSubject
会保留最后一次发布的值。当有人订阅它时,它也会发出last/inital
持久值。
//it needs initial state while registering it, so passed false
private isSuccess = new BehaviorSubject<boolean>(false);