Melchia
Melchia

Reputation: 24294

Can't pass objects returned by Observable as input component Angular 5

I have a small component where I have only one input

Ts component Code

 @Input() variables;

      ngOnInit() {
        console.log(this.variables);
    }
   

Where I use my component TS

envVars$: Observable<{
            names: String[],
            values: {}
          }>;

Where I use my component HTML

 <app-code  [variables]="(envVars$ | async)?.values | json"></app-code>
 

In the console log I HAVE NULL though my object is full

Upvotes: 2

Views: 553

Answers (1)

bryan60
bryan60

Reputation: 29335

the log says null because you're logging ON INIT before the object has been asynchronously defined. The async pipe is working exactly as intended. if you need the object to be defined on init then you need to change your structure a little.

do this instead to ensure the observable is populated prior to component instantiation:

<app-code *ngIf="envVars$ | async as enVars" [variables]="envVars.values | json"></app-code>

the ngIf here tells angular to not instantiate the component until envVars$ emits a value.

Upvotes: 1

Related Questions