Angular 8问题,订阅了服务中的变量

问题描述 投票:0回答:1

我正在学习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个回答
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(); }
    
© www.soinside.com 2019 - 2024. All rights reserved.