📜  map vs subscribe angular - Javascript(1)

📅  最后修改于: 2023-12-03 15:17:31.962000             🧑  作者: Mango

Map vs Subscribe in Angular

When working with Observables in Angular, it's common to encounter the map and subscribe operators. While both are used to modify the behavior of Observables, they serve different purposes, and understanding their differences is crucial for building effective applications.

Map Operator

The map operator is used to transform the emitted values of an Observable into a new form. For example, let's say we have an Observable that emits the current temperature in Fahrenheit:

import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class WeatherService {
  constructor(private http: HttpClient) {}

  getCurrentTemperature() {
    return this.http.get('http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=YOUR_APP_ID')
      .pipe(
        map(response => {
          const temperatureInKelvin = response['main'].temp;
          const temperatureInCelsius = temperatureInKelvin - 273.15;
          return temperatureInCelsius;
        })
      );
  }
}

In this example, we call the OpenWeatherMap API to fetch the weather data for London, UK. We then apply the map operator to the resulting Observable to transform the temperature from Kelvin to Celsius.

Note that the map operator returns a new Observable that emits the transformed value. We can then subscribe to this Observable to receive the transformed value.

Subscribe Operator

The subscribe operator is used to receive the emitted values of an Observable and perform some action based on those values. For example, let's say we have an Observable that emits the current temperature in Fahrenheit:

import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class WeatherService {
  constructor(private http: HttpClient) {}

  getCurrentTemperature() {
    return this.http.get('http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=YOUR_APP_ID');
  }
}

In this example, we call the OpenWeatherMap API to fetch the weather data for London, UK. We can then subscribe to this Observable to receive the emitted values:

import { Component, OnInit } from '@angular/core';
import { WeatherService } from './weather.service';

@Component({
  selector: 'app-weather',
  templateUrl: './weather.component.html',
  styleUrls: ['./weather.component.css']
})
export class WeatherComponent implements OnInit {
  currentTemperature: number;
  
  constructor(private weatherService: WeatherService) {}

  ngOnInit() {
    this.weatherService.getCurrentTemperature().subscribe(response => {
      const temperatureInKelvin = response['main'].temp;
      const temperatureInCelsius = temperatureInKelvin - 273.15;
      this.currentTemperature = temperatureInCelsius;
    });
  }
}

In this example, we subscribe to the Observable returned by the getCurrentTemperature method and update the currentTemperature property of our component with the transformed value.

Note that the subscribe operator returns a Subscription object, which can be used to unsubscribe from the Observable when we no longer need to receive its values.

Conclusion

In summary, the map operator is used to transform the emitted values of an Observable into a new form, while the subscribe operator is used to receive the emitted values of an Observable and perform some action based on those values. By understanding the differences between these operators, we can build more effective applications with Observables in Angular.