Neekoy
Neekoy

Reputation: 2543

RxJS ReplaySubject not updating Angular Zone

I have a ReplaySubject variable that's being updated on a service, and the component is properly getting the new values, however it doesn't seem to update the view (The binding in HTML stays empty, even though the variable is properly updated).

Service:

export class ExampleService {
  myVariable;

  constructor(private http: HttpClient, private userModel: UserModel) { 
    this.myVariable = new ReplaySubject(1);

    this.getApiRoot(`/api/endpoint`)
    .subscribe(
      data => { 
        this.myVariable.next(data);
      },
      err => { 
        console.log(`Database connection error: ${err}`);
      },
      () => { }
    );
  }
}

Component:

import { ExampleService } from './example.service'; export class myComponent implements OnInit {

valueOnFrontend: string;

constructor(exampleService: ExampleService) {};

ngOnInit() {
    this.exampleService.myVariable.subscribe(
    function(value) {
        console.log(this.valueOnFrontend);
        this.valueOnFrontend = value;
    },
    function(error) {
        console.log(err);
    },
    function() {
        console.log("Request completed.");
    }

) } }

And the HTML for ExampleService is the following:

{{ valueOnFrontend }}

So the value is being updated properly in the service, then it's being emitted properly to the component, the console.log in the component logs the new value, however the HTML binding isn't getting updated.

I read that RxJS runs in its own Zone, and the Angular Zone isn't aware of updates in it. How can I fix this, and get the value to update in the HTML too?

Thanks. :P

Upvotes: 0

Views: 1023

Answers (2)

conpile
conpile

Reputation: 66

is it an option for you to access the observable exampleService.myVariable via the async pipe in the template without subscribing in the code behind? like:

{{exampleService?.myVariable | async}}

Upvotes: 1

Lucho
Lucho

Reputation: 1547

The subscribe callback in your component should use fat arrow for correct scope

this.exampleService.myVariable.subscribe( 
  (value: any) => { 
    console.log(this.valueOnFrontend);
    this.valueOnFrontend = value; 
  }, 
  (error: any) => { 
    console.log(err); 
  }, () => { 
    console.log("Request completed."); 
  }
);

Upvotes: 0

Related Questions