【问题标题】:Angular 8 issue with subscribing to variable in serviceAngular 8 订阅服务中的变量的问题
【发布时间】:2020-01-20 23:56:56
【问题描述】:

我正在学习 Angular 并尝试监听一个保存 http 请求值的变量。这是服务

export class UsersService {
 message = new Subject<string>();
 constructor(private http: HttpClient) { }
 addUser(userData: {username, email, password, school}) {
   this.http.post<any>('http://127.0.0.1/apiapp/insert.php', userData).subscribe( (r) => {
     this.message = r.message;
   });
}

当我记录消息时,我收到success 现在我想调用这个函数并从组件中监听那个变量

result = '';
private resultSubscription: Subscription;

  ngOnInit() {
    this.resultSubscription = this.userS.message.subscribe( (r) => {
      this.result = r;
    });
 }

  addPost(userData: {username: string, email: string, password: string, school: string}) {
    this.userS.addUser(userData);
    console.log(this.result);    
 }

我得到一个空白数据(没有记录只是控制台中的一个空白行)。为什么会这样以及如何解决? 提前致谢

【问题讨论】:

    标签: angular rxjs httprequest listener rxjs6


    【解决方案1】:

    这里有 3 个问题。

    • 您没有通过主题正确发送值
    • 您的console.log(this.result) 的位置存在一些异步问题
    • 您需要在您的主题上调用 .asObservable 以获得可观察的主题

      export class UsersService {
          message = new Subject<string>();
          constructor(private http: HttpClient) { }
      
          addUser(userData: {username, email, password, school}) {
              this.http.post<any>('http://127.0.0.1/apiapp/insert.php', userData).subscribe( (r) => {
              // .next is how you send data via a subject
              this.message.next(r.message);
          });
      }
      
      
      
      
      result = '';
      private resultSubscription: Subscription;
      
      ngOnInit() {
          // Get subject as observable
          this.resultSubscription = this.userS.message.asObservable().subscribe( (r) => {
              this.result = r;
              // by logging here we can ensure that the result will be populated
              console.log(this.result);  
          });
      }
      
      addPost(userData: {username: string, email: string, password: string, school: string}) {
          this.userS.addUser(userData);
      }
      
      // It is important to unsubscribe for your observable when the component is destroyed
      ngOnDestroy(): void { this.resultSubscription.unsubscribe(); }
      

    【讨论】:

    • ngOnDestroy(): void { this.resultSubscription.unsubscribe();在这种情况下,这对于防止内存泄漏很重要吗?
    • @PHPUser 你是对的,完全忘记了这一点。我的道歉
    猜你喜欢
    • 1970-01-01
    • 2016-06-03
    • 2020-05-18
    • 2020-01-26
    • 1970-01-01
    • 2022-12-06
    • 2020-06-23
    • 2020-06-21
    • 2020-10-26
    相关资源
    最近更新 更多