0

请查看此 GitHub 存储库https://github.com/nileshzala005/Service-demo

userService在根级别注册。

我想在's中获得getUserLogin可观察的价值。当用户单击按钮时,将从.SharedModuleUserComponentHomeComponentHomeModule

UserService在根级别:

userLogin = new Subject<string>();

  constructor() { }
  sendUserLogin(user: string) {
    console.log("value received at user service ", user);
    this.userLogin.next(user);
  }
  getUserLogin(): Observable<string> {
    return this.userLogin.asObservable();
  }

HomeComponentHomeModule

export class HomeComponent implements OnInit {

  constructor(private userService: UserService) {

  }

  ngOnInit() {
  }
  onClick() {
    console.log("value is send from home component", "Nilesh")
    this.userService.sendUserLogin("Nilesh");
  }

}

UserComponentSharedModule

export class UserComponent implements OnInit {

  constructor(private userService: UserService) { }

  ngOnInit() {
    this.userService.getUserLogin().subscribe(res => {
          /// here it should receive but not able to get it
      console.log("user component should get value here ", res);
    });
  }

}

控制台日志

4

2 回答 2

1

您需要使用 BehaviorSubject 而不是 Subject 来获取发出的值。检查这篇文章以获得解释。语法有点过时,但它仍然遵循相同的概念

主题和行为主题有什么区别?

于 2019-12-05T11:02:03.127 回答
0

尝试使用BehaviorSubject而不是Subject. 即使订阅是在发出值之后完成的,它也会将最后一个值发送到订阅。

可能是您在发出值后订阅的问题。

于 2019-12-05T11:02:51.760 回答