Home > database >  Subscribe to observable/subject (declared in a service)
Subscribe to observable/subject (declared in a service)

Time:03-04

I like to get the last value of an observable and use this in my html. When a value is emited (next) then the html must auto update as well The last value also must be used in a funtion as a (string) variable.

Do I have too much code for this issue or am I missing a subscibtion or something else?

Service

export class someService {
  lastUsedSubject = new BehaviourSubject<string>(null);
  lastUsed$ = this.lastUsedSubject.asObservable();
}

updateLastUsed(id: string) {
  this.lastUsedSubject.next(id);
}

component (in the onit I subscribe on a valuechange that will trigger the update some

@Component({
export class someComponent implements Oninit { 
      lastUsed$: Observable<string>;
    
      ngOnInit(): void {
        this.formGroup.get("items").valueChanges.subscribe((val: string) => {
          this.someService.updateLastUsed(val);
        }
      }
    
      someFunction() {
        // I can use this.someService.lastUsedSubject.value to get latest value
        // service is declared in constructor
        // lastused must be a string
        somemethodcall(lastused, anotherparam);
      }
    })
}

HTML

--{{lastUsed$ | async}}--

CodePudding user response:

Use async pipe

--{{lastUsed$ | async}}--

CodePudding user response:

In your template you are using lastUsed$ from the component, though, the actual value is being updated in the service, I think you should access the Observable from the service instance, smth like:

@Component()
constructor(public someService: SomeService) {}
@template
{{ someService.lastUsed$ | async }}

Or you can init the observable in the component from the service Subject, smth like

@Component
lastUsed$ = this.someService.lastUsedSubject.asObservable();
  • Related