簡體   English   中英

角; 在這些組件之間共享數據

[英]Angular; Sharing data between this components

我是Angular的新手,我在這里遇到這個問題:我想將我從該service +組件獲得的數據傳遞給另一個組件。

我有這樣做的服務:

getRecs() {

    let recsSub = new Subject<any>();
    let recsSubObservable = from(recsSub);

    this.socket.on('recs', (recsStatus: any) => {
        recsSub.next(recsStatus);
    });

return recsSubObservable;
}

然后我有這個父組件

private misRecs = null;
snackBarShown = false;

constructor (private appSocketIoService: AppSocketIoService, private snackbar: MatSnackBar) {

 let recsObservable =  this.appSocketIoService.getRecommendations();

 recsObservable.subscribe((recsStatus: any) => {
   console.log(recsStatus);
   this.misRecs = {};

    for(let property in recsStatus.output){
      if (recsStatus.output[property]) {
        this.misRecs[property] = recsStatus.output[property];
      }
    };

    this.snackbar.openFromComponent (CustomSnackBar, { duration: 5000, });

 });
 }

我需要的是用從recsStatus獲得的值填充另一個組件中的列表,但是我不知道該怎么做。

謝謝大家的幫助。

如果該組件是您的組件(父)的子組件,則可以使用@Input()注釋。

@Component({
    selector: 'child-comp',
    template: `
    <div>
        {{ localRecStatus | json }}
    </div>
   `
})
export class ChildComponent {
    @Input()
    localRecStatus: [];
}

現在,您可以像下面這樣使用父組件的HTML文件中的組件:

<child-comp [localRecStatus]="recStatus"></child-comp>

這樣,您可以在子組件中使用recStatus。 但是, recStatus必須是父組件的公共變量。 使用這種技術,您可以將任何數據傳遞給子組件。 還有一個@Output()批注,可以與EventEmitter結合使用,以將數據發送到父組件。 如果組件不是子組件,則可能更好的方法是通過服務在兩個組件之間進行通信。

暫無
暫無

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

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