I'm trying to subscribe to a BehaviourSubject
that was set by parent component and get it in the child one, i'm trying to make the following in my component:
export class ModuliComponent implements OnInit {
public profilo: Profilo;
constructor(public profiloService: ProfiloService) { }
ngOnInit(): void {
this.profiloService.dataProfilo.subscribe(data => this.profilo = data); // setting profilo
}
}
But when i try to use profilo
in HTML i just get undefined
on asporto
or other *ngIf
What i'm doing wrong? should i initialize first the profilo
? if so even by setting onInit
or in constructor
the profilo = new Profilo();
i get the same error of undefined...
If i set a console.log to subscribe it return the right data, so asporto and other stuff from subscribe are not undefined.
As requested here is ProfiloService
@Injectable({
providedIn: 'root'
})
export class ProfiloService {
public dataProfilo = new BehaviorSubject<any>([]);
constructor(private http: HttpClient, private adapter: ProfiloAdapter) { }
profilo(idNegozio: string): Observable<Profilo>{
return this.http
.get(`${Globals.API_URL}/profilo/${idNegozio}`)
.pipe(map((data: any) => this.adapter.adapt(data)));
}
}
And here is the component where i'm setting the dataProfilo:
this.profiloService.dataProfilo.next(profilo);
Console.Log from subscribe data
EDIT:
If i add on parent div *ngIf="profilo.moduli"
it will works fine, but at this point if profilo is undefined why it is not enough to do a simple *ngIf="profilo"
?
ProfiloService
– Satpalsubscribe
can you doconsole.log(data)
and please update your question with console data or image of console – Sivakumar TadisettiBehaviorSubject
to newBehaviorSubject<any>(new Profilo);
and i will do a*ngIf="profilo.id"
instead of*ngIf="profilo"
it will works, but i would a cleaner solution where i have profilo undefined and*ngIf="profilo"
– Kasper Juner