(Following the suggestion so gunnar, i'm editing my question) @Gunnar.B
Service for connection with api
@Injectable({
providedIn: 'root'
})
export class ConsolidadoApi {
constructor(private http: HttpClient) { }
getInvestiments(search?: any): Observable<any> {
return this.http.get<any>(`${environment.basePosicaoConsolidada}`);
}
}
This service (layer) exposes the streams of state and interface for the components in the presentation layer(component)
@Injectable({
providedIn: 'root'
})
export class CoreService {
constructor(private api: ConsolidadoApi, private state: StateService) { }
public getInvestments$(): Observable<any> {
return this.state.getInvestiments$()
}
public loadInvestments() {
return this.api.getInvestiments()
.pipe(
tap(investPortifolio => this.state.setInvestments(investPortifolio))
);
}
}
This service is responsible for the logic that will go to the component
@Injectable({
providedIn: 'root'
})
export class StateService {
private investments$ = new BehaviorSubject<any>(null);
public getInvestiments$() {
return this.investments$.asObservable()
}
public setInvestments(investPortifolio){
this.investments$.next(investPortifolio)
}
}
However in my html does not appear the data coming from the api.
menu.component.ts
export class MenuComponent implements OnInit {
investments$: Observable<any>;
constructor( private coreService : CoreService ) {
this.investments$ = this.coreService.getInvestments$()
}
ngOnInit(): void {
this.coreService.loadInvestments();
console.log(this.coreService.loadInvestments())
}
}
menu.component.html
<div>
test
</div>
<div *ngFor="let investimentPortifolio of investments$ | async;">
{{investimentPortifolio | json}}
</div>
listInvestments method is performing an asynchronous API call. So basically the investments property still have undefined when you called forEach on it.
You want to loop in investments array after you load data from the server not before.
One way to do it is to make sure you are inside subscribe's next() callback and there you are certain you have the data you need to perform your action.
CoreService class becomes:
@Injectable({
providedIn: 'root'
})
export class CoreService {
public investments: any;
constructor(private api: ConsolidadoApi, private state: StateService) {}
public createMenu(){
this.api.getInvestments()
.subscribe(response => {
this.investments = response;
this.investments.forEach(element => {
console.log(element)
});
})
}
}
In ngOnInit you called loadInvestments() that returns an observable. And observable are lazy, that means if you didn't call subscribe on them nothing will happen.
What you need to do is change this line:
this.coreService.loadInvestments();
to
this.coreService.loadInvestments().subscribe();