簡體   English   中英

在子組件中使用@input屬性調用Angular 2中的服務

[英]Using @input property in child component to call service in angular 2

使用角度2中的@input從父組件到子組件的通信數據。我的目的是我想使用值參數@input調用子組件中的服務,但value屬性為“ undfine”。 這是我的孩子部分:

import { Component, OnInit,  EventEmitter, Input,Output } from     '@angular/core';

@Component({
    selector: 'app-child', 
    templateUrl: './child.component.html'
})

export class ChildComponent  implements OnInit {


    @Input() productId: any; --> working perfectly if bind into html

    constructor() {

    }

    ngOnInit(): void {
        console.log(this.productId) --> undefine?
    //in this methode i will call service to fetch another data from database using parameter productId..


    }
}

如何解決呢?

我會使用一個吸氣劑和一個塞特,在塞特內部,您將撥打服務電話。

// Declare a private underlying variable for the getter and setter
private _productId: any;
@Input()
set productId(id: any){
    this._productId = id;
    // Make your service call here
}
get productId(){
    return this._productId;
}

您需要使用ngOnChanges或ngAfterViewInit:

export class ChildComponent  implements OnChanges {
    // Subscribe to the change event and update the model
    ngOnChanges(changes: {[propName: string]: SimpleChange}) {
        let key = 'Data';
        this.productId = changes[key].currentValue;
    }
}
@Input() 
set productId(value: any) {
  console.log(value);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM