簡體   English   中英

將數據從服務傳遞到父組件,然后從父組件傳遞到子組件

[英]Passing data from service to parent then from parent to child component

好的,伙計們,我是Angular的新手,但我遇到了問題,我不知道自己在做什么錯。

我的父組件看起來像這樣,我正在嘗試將每周變量傳遞給我的子組件:

app.component.ts

import { Component } from "@angular/core";
import { GeolocationService } from "./geolocation.service";
import { WeatherService } from "./weather.service";
import { kmphToMs } from '../utilities/helpful';

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  latitude: number;
  longitude: number;
  cityName: string;
  currentTemp: number;
  currentHumidity: number;
  currentWindSpeed: string;
  weekly: Array<object>;
  erroMessage: string;

  constructor(
    private geolocationService: GeolocationService,
    private weatherService: WeatherService
  ) {}

  ngOnInit() {
    this.geolocationService.getCoordinates().subscribe(result => {
      console.log(result);
      this.latitude = result.coords.latitude;
      this.longitude = result.coords.longitude;
      this.weatherService
        .getTheWeather(this.latitude, this.longitude)
        .subscribe(weatherData => {
          console.log(weatherData);
          this.cityName = weatherData["timezone"];
          this.currentTemp = weatherData["currently"]["temperature"];
          this.currentWindSpeed = kmphToMs(weatherData["currently"]["windSpeed"]);
          this.currentHumidity = weatherData['currently']['humidity'] * 100;
          this.weekly = weatherData['daily']['data'];
          console.table(this.weekly);
        });
    });
  }
}

app.component.html

  <app-days
    [weekly]="weekly"
  ></app-days>

這就是我的子組件的樣子:

import { Component, OnInit, Input } from "@angular/core";

@Component({
  selector: "app-days",
  templateUrl: "./days.component.html",
  styleUrls: ["./days.component.css"]
})
export class DaysComponent implements OnInit {
  @Input() weekly: Array<object>;


  constructor() {
  }

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

我正在嘗試console.log每周變量,但是它說它是未定義的,我不知道為什么

在您的訂閱完成之前,您的AppComponent模板將開始加載。 在此之前, weekly變量將在AppComponent上未定義。

嘗試在ngOnChanges閱讀它。 每次在Component上更改@Input屬性時,就會調用此@Input 因此,只要在AppComponent中weekly初始化一次,就會使用更新后的weekly值調用ngOnChanges

import { Component, OnChanges, Input } from "@angular/core";

@Component({
  selector: "app-days",
  templateUrl: "./days.component.html",
  styleUrls: ["./days.component.css"]
})
export class DaysComponent implements OnChanges {
  @Input() weekly: Array<object>;

  constructor() {
  }

  ngOnChanges() {
    console.log(this.weekly); 
  }

}

為了防止出現undefined值,您可以在AppComponent的模板中放置*ngIf

<app-days *ngIf="weekly" [weekly]="weekly" ></app-days>

您的GEO服務正在異步設置每周變量。 因此,到子組件的ngOnInit方法被調用時,父組件中的異步調用可能尚未完成。

在子模板html中添加{{weekly | json}},以調試是否設置了數據。

每周的原因最初在AppComponent中未定義,並從結果geolocationService.getCoordinates()異步填充。

但是,在DaysComponent中,您嘗試引用ngOnInit掛鈎上的每周數據,這不保證此服務調用將完成。

以下是您可以做的一些建議:

  1. 根據每周的存在情況將ngIf指令添加到app-days中。 要么,

  2. 在DaysComponent中實現OnChanges,並在每周輸入更改時繼續工作。

  3. 您可以通過“主題/可觀察”來宣布更改,並偵聽組件中的更改並做出相應的反應。

暫無
暫無

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

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