Angular 订阅服务中的变量时出现 8 个问题

Angular 8 issue with subscribing to variable in service

我正在学习 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);    
 }

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

您有 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(); }