Search code examples
angularobservableangular-servicesangular-pipeangular-observable

Angular Service with Observable implementation


I've followed many examples to try and get this working but struggling and there seems to be many different ways - so thought best to come here and get an answer.

In simple terms... I have a component that I want to load some data from a JSON file on creation and display it when the data has been loaded.

appData.model.ts

export interface AppData {
    lastUpdated: string;
}

data.service.ts

  getData(): Observable<AppData> {
    return this.http.get<AppData>('data.json?noCache=' + Math.random());
}

test.component.ts

export class TestComponent implements OnInit {
  obsAppData: Observable<AppData>

  constructor(private dataService: DataService) { }

  ngOnInit() {
    console.log('Test ngOnInit()');
    this.obsAppData = this.dataService.getData();
  }

I've then tried to print the value of lastUpdated to the component by using the following code in the html template:

{{ obsAppData.lastUpdated | async }}

I get no errors in the console but nothing is printing out! Can anyone see anything wrong with the code or any constructive advice on how to debug where the issue is? I think I've picked up Angular quite well, but safe to say I'm struggling with the Observable side of things.


Solution

  • Ahhh i just noticed you are using it wroong. This should work

    {{ (obsAppData | async).lastUpdated  }}