0
votes

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

2
" this.valueOnFrontend = value;" is this reference the component object?ABOS
@ABOS Yep, exactly. It's the value of the variable on the frontend.Neekoy
clearly not, as you replied below. always pay attention to the scope of "this" in callbacks.ABOS
Ah, my impression was that I was referencing the correct variable, the scope was wrong though. Now I understand you question. Cheers.Neekoy

2 Answers

1
votes

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}}
0
votes

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."); 
  }
);