【问题标题】:Pass async data to component as parameter将异步数据作为参数传递给组件
【发布时间】:2017-12-22 11:45:17
【问题描述】:

我正在尝试制作一个自定义选择组件,它的数据异步加载并作为参数传递。这是我的组件:

@Component({
    selector: 'custom-select-combo',
    template:
    `<select #CustomSelectCombobox
        class="form-control"
        [(ngModel)]="selectedOption"
        (ngModelChange)="selectedOptionChange.emit($event)"
        [attr.data-live-search]="true">        
            <option *ngFor="let item of items | async" [value]="item">{{item}}</option>
    </select>`
})
export class CustomSelectComboComponent extends AppComponentBase implements OnInit, AfterViewInit {

    @ViewChild('CustomSelectCombobox') customSelectComboboxElement: ElementRef;

    @Input() selectedOption: string = undefined;
    @Input() items: string[];
    @Output() selectedOptionChange: EventEmitter<string> = new EventEmitter<string>();

    constructor(
        injector: Injector) {
        super(injector);
    }

    ngOnInit(): void {
        const self = this;
        setTimeout(() => {
            $(self.customSelectComboboxElement.nativeElement).selectpicker('refresh');
        }, 0);
    }

    ngAfterViewInit(): void {
        $(this.customSelectComboboxElement.nativeElement).selectpicker({
            iconBase: 'famfamfam-flag',
            tickIcon: 'fa fa-check'
        });
    }
}

这是html:

<div class="col-xs-6">
    <custom-select-combo [items]="tipoItems"></custom-select-combo>
</div>

这是我加载数据的地方:

tipoItems = [];

constructor(
    injector: Injector,
    private _tipoDadoService: TipoDadoServiceProxy,
) {
    super(injector);
    this._tipoDadoService.getAllTipos()
        .subscribe((result) => {
            this.tipoItems = result;
        });
}

当我尝试运行此实际代码时,控制台中出现错误:

“错误错误:InvalidPipeArgument: '' for pipe 'AsyncPipe'”

还有很多

“ERROR TypeError: Cannot read property 'dispose' of null”。

我尝试阅读一些教程,但仍然无法使用。

@编辑: 服务等级,按要求:

@Injectable()
export class TipoDadoServiceProxy {
    private http: Http;
    private baseUrl: string;
    protected jsonParseReviver: (key: string, value: any) => any = undefined;

    constructor(@Inject(Http) http: Http, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
        this.http = http;
        this.baseUrl = baseUrl ? baseUrl : "";
    }
    /* Whole bunch of other functions here... */

    /**
     * @return Success
     */
    getAllTipos(): Observable<string[]> {
        let url_ = this.baseUrl + "/api/services/app/TipoDado/GetAllTipos";
        url_ = url_.replace(/[?&]$/, "");

        const content_ = "";

        let options_ = {
            body: content_,
            method: "get",
            headers: new Headers({
                "Content-Type": "application/json; charset=UTF-8", 
                "Accept": "application/json; charset=UTF-8"
            })
        };

        return this.http.request(url_, options_).flatMap((response_) => {
            return this.processGetAllTipos(response_);
        }).catch((response_: any) => {
            if (response_ instanceof Response) {
                try {
                    return this.processGetAllTipos(response_);
                } catch (e) {
                    return <Observable<string[]>><any>Observable.throw(e);
                }
            } else
                return <Observable<string[]>><any>Observable.throw(response_);
        });
    }

    protected processGetAllTipos(response: Response): Observable<string[]> {
        const status = response.status; 

        if (status === 200) {
            const responseText = response.text();
            let result200: string[] = null;
            let resultData200 = responseText === "" ? null : JSON.parse(responseText, this.jsonParseReviver);
            if (resultData200 && resultData200.constructor === Array) {
                result200 = [];
                for (let item of resultData200)
                    result200.push(item);
            }
            return Observable.of(result200);
        } else if (status !== 200 && status !== 204) {
            const responseText = response.text();
            return throwException("An unexpected server error occurred.", status, responseText);
        }
        return Observable.of<string[]>(<any>null);
    }


}

【问题讨论】:

  • @AllenWahlberg 完成

标签: angular typescript asynchronous


【解决方案1】:

您最好使用 ControlValueAccessor。这需要实现一些方法,然后您将能够使用 ngModel 或将此自定义组件用作表单控件。 此处示例:https://jenniferwadella.com/blog/Angular-2-forms-CVA-intro

【讨论】:

    【解决方案2】:

    试试看

    HTML

    <div class="col-xs-6" *ngIf="(tipoDadoService.getAllTipos | async) && tipoDadoService.getAllTipos.getValue().length">
        <custom-select-combo [items]="_tipoDadoService.getAllTipos.getValue()"></custom-select-combo>
    </div>
    

    对于组件

    constructor( 
        public tipoDadoService: TipoDadoServiceProxy,
    ) { 
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-16
      • 2020-12-27
      • 2017-12-17
      • 1970-01-01
      • 1970-01-01
      • 2020-03-06
      • 1970-01-01
      • 2019-01-13
      • 2012-10-17
      相关资源
      最近更新 更多