简体   繁体   中英

Angular - Pass an Observable as @Input

I have a component and I want to pass an observable as input

<selective [source]="areasService.getSelectAreas()" placeholder="Select Items"></selective>

and use it inside the component

@Input() source;
ngOnInit(): void {
    this.searchField = new FormControl();
    this.selectiveForm = this.fb.group({
        search: this.searchField
    });
    console.log(this.source);

    this.sub = this.searchField.valueChanges
        .startWith('')
        .debounceTime(200)
        .flatMap(key => this.source)
        .subscribe((result) => {
            this.list = result.json().data.areas;
            this.countItems = this.list.length;
        });

}

but I get this error "Property 'json' does not exist on type '{}'."

If I inject the service areasService into the component and use it as this.areasService.getSelectAreas() it works fine

But I doesn't work if i pass it as parameter

I am guessing that getSelectAreas is asynchronous, which means it wouldn't have returned any data when ngOnInit is called on the child component. You could get around this by implementing ngOnChanges , but that probably would not be the best solution here:

Note that it's generally not a good idea to bind a function call to a component, as it will be called constantly . I would either unwrap areasService.getSelectAreas() to a value in the controller, or if areasService.getSelectAreas() is a Promise or Observable you can use the async pipe to have Angular unwrap it for you, like so:

<selective [source]="areasService.getSelectAreas | async" placeholder="Select Items"></selective>

If it returns a Promise or Observable, just assign that return value to a variable in the component and bind that instead with the the async pipe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM