我正在创建一个天气应用程序。
我有view.component
,coord.service
,weather.service
。
我有view.component
用户输入。我想将组件的输入传递给coord.service
,后者进行API调用并返回坐标。坐标应传递给weather.service
,view.component
也进行API调用,并将Observable返回view.component.ts
以呈现为HTML。我无法弄清楚/理解如何实现这一目标。
@Component({
selector: 'app-view',
templateUrl: './view.component.html',
styleUrls: ['./view.component.css']
})
export class ViewComponent implements OnChanges {
alerts: any;
currData:any = {};
@Input() location: string;
coordinate = [];
constructor(public weatherService: WeatherService) { }
ngOnChanges(changes: SimpleChanges) {
// pass location to coord.service -> i don't know what to do from here
//this.weatherData(this.coordinate);
}
weatherData(coord: Array<number>) {
this.weatherService.getWeatherInfo(coord).subscribe((data) => {
// do something with data and make it render
});
}
:
coord.service
@Injectable({
providedIn: 'root'
})
export class CoordinateService {
readonly coord_API = ""
constructor(private http : HttpClient) { }
getCoordinates(location : string) {
return this.http.get(this.coord_API.replace("*", location)).pipe(
tap(_ => console.log("recieved geoData")),
catchError(err => {throw "GEO ERROR: " + err})
)
}
}
weather.service
@Injectable({
providedIn: 'root'
})
export class WeatherService {
readonly weather_api : string = "";
coordinates : [] = [];
// I need to pass in input from component to coordService
constructor(public http : HttpClient, public coordinateService : CoordinateService) { }
getWeatherInfo(coordinates : Array<number>, type="daily") {
return this.http.get(this.weather_api).pipe(
tap(_ => console.log('got data')),
catchError(err => {throw "WE. ERR : " + err})
);
}
}
constructor(
public weatherService: WeatherService,
public coordsService: CoordinateService,
) { }
weatherData() {
this.coordsService.getCoordinates('your param').pipe(
switchMap(coords => this.weatherService.getWeatherInfo(coords))
).subscribe(data => console.log(data));
}
您的组件应聚合服务并进行调用。
switchMap
服务是可以注入Angular中任何内容的提供者。它们应该有一个目的:组件应该能够使用它们并将它们组合在一起。
reactive programming是一名RxJS运营商。
RxJS是Angular广泛使用的库,它使subscribe
成为可能。当您进行HTTP调用时,您将创建一个通过a lot of operators关键字创建的观察者。这会创建一个流,其中数据是不可变的。
RxJS允许您使用运算符来操作流。你有switchMap
可供选择。
在switchMap
的情况下:这是一个允许您将流切换为另一个的运算符。这意味着首先请求坐标,然后使用mergeMap
请求天气,以及第一次http调用的结果。
你有几个运算符,比如flatMap
,switchMap
......但是qazxswpoi应该永远是第一选择,因为如果再次观察到observable,它会取消任何待处理的请求。这意味着如果用户连续多次单击该按钮,则会取消待处理的请求,从而减少http调用。