首页 > 解决方案 > 更新值时如何正确绑定组件以刷新?

问题描述

我有一个简单的应用程序,目的是获取某个位置的当前天气。该位置具有默认值,但其中一个组件具有应更改位置、调用 API 并重新显示数据的按钮。

所以我有两个组件:Location 和 WeatherDisplay。我还有一个服务可以完成繁重的工作(基本上是调用 API)。

我的问题是当用户点击一个新位置时 WeatherDisplay 不会改变。我是 Angular 的初学者,所以如果我在这个“演示文稿”中遗漏了什么,请告诉我。

我尝试了许多不同的东西,我认为我已经将它缩小到 API 服务中的某些东西。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { MessageService } from './message.service';
import { BehaviorSubject } from 'rxjs';
import { WeatherStruct } from './weather';

const API_URL = 'http://api.openweathermap.org/data/2.5/weather';
// my key for the OpenWeatherAPI
const API_KEY = '3f25...'; // deleted most of what my key is just 'cause
// default location
const LOCATION_ID = '4480285'; // Morrisville, NC
// get the value from the message

@Injectable({
    providedIn: 'root'
})
export class APIService {
    private locationSource: BehaviorSubject<any> = new BehaviorSubject(null);
    currentLocation = this.locationSource.asObservable();

    constructor(
        private httpClient: HttpClient,
        private msgService: MessageService
    ) {}

    getWeather(loc_id = '4480285'){
        // this.msgService.add('api.service.ts '+loc_id);
      console.log('api.service getWeather('+loc_id+')');
      const api_string = `${API_URL}?id=${loc_id}&APPID=${API_KEY}&units=imperial`;
      console.log(api_string);
      return this.httpClient.get(api_string);
  }

    changeLocation(locid: string) {
        console.log('api.service changeLocation('+locid+')');
        this.locationSource.next(locid);
        // need to tell weather-display to re-fetch the data
        this.getWeather(locid);
    }
}

在我的位置组件模板中:

<button (click)="newLocation('5391811')">San Diego, CA</button>

天气显示组件:

import { Component, OnInit } from '@angular/core';
import { MessageService } from '../message.service';
import { WeatherStruct } from '../weather';
import { APIService } from '../api.service';

@Component({
    selector: 'app-weather-display',
    templateUrl: './weather-display.component.html',
    providers: [APIService],
    styleUrls: ['./weather-display.component.css']
})

export class WeatherDisplayComponent implements OnInit {
    weather: WeatherStruct;
    private today: number = Date.now();
    loc_id: string;

    constructor(
        private apiService: APIService,
        private msgService: MessageService
    ) {}

    ngOnInit() {
        this.apiService.currentLocation
            .subscribe(location => this.loc_id = location);
        this.fetchWeather();
        console.log('CCC');
    }

    fetchWeather(loc_id = '4480285') {
        console.log('weather-display.component showWeather(' + loc_id + ')');
        this.apiService.getWeather(loc_id).subscribe((data: WeatherStruct) => {
            this.weather = data;
            this.weather['today'] = this.today;
        });
    }
}

在 location.component.ts 中:

export class LocationComponent implements OnInit {
    location: string;

    @Output() talk: EventEmitter<string> = new EventEmitter<string>();

    constructor(private apiService: APIService,
        private msgService: MessageService) {}

    ngOnInit() {
        this.apiService.currentLocation.subscribe(
            location => (this.location = location)
        );
    }

    newLocation(newLoc: string) {
        console.log('location.component newLocation('+newLoc+')');
        // use an event emiitter 
        this.talk.emit(newLoc);
        // call a function in the service
        this.apiService.changeLocation(newLoc);
    }
}

最后在 app.component.ts

export class AppComponent implements OnInit {

    location: string;

    constructor(private apiService: APIService) {}

    title = 'The Weather';

    ngOnInit() {
        this.apiService.currentLocation.subscribe(
            location => (this.location = location)
        );
    }
    goGetWeather(newLoc){
        console.log("app.component.goGetWeather("+newLoc+")");
    }
}

当我执行我的应用程序并尝试单击一个按钮时,我看到代码按我的预期执行:

location.component newLocation()被调用,它调用 app.component.goGetWeather [告诉我事件发射器正在工作];和 api.service changeLocation,这会导致 api.service getWeather生成正确格式的 API 字符串来调用

http://api.openweathermap.org/data/2.5/weather?id=2643743&APPID=3f25...&units=imperial

但 DisplayWeather 组件没有任何变化。

我知道这很简单,但我就是无法指出它出了什么问题。

标签: angulardata-binding

解决方案


这可以通过使用共享服务来实现。如何实现共享服务参考链接:http ://www.angulartutorial.net/2017/09/angular-share-data-between-components.html

代码如下所示:

服务.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class SharedService {
    // Subject (emitter) for User Name Change
    CityNameChange: Subject<string> = new Subject<string>();

    // SetUserChange() - This method sets the local variable and emits the change
    SetCityChange(param: string) {
        this.CityNameChange.next(param);
    }
}

在您的第一个组件中单击城市更改调用 service.setCityChange() 的按钮

this._sharedService.SetCItyChange(newCityName);

在您的第二个组件中,在 ngOnInit 中订阅 city Change 事件并获取基于新城市的天气数据:

this._sharedService.UserNameChange
  .subscribe((value) => {
    // Get the weather information
  });

推荐阅读