Search code examples
angularxmlhttprequestcomponents

Angular 4: How to use http request response in different component?


I am working in Angular4, and trying to use a http get request response in another function (I have a hotel-list component, I can select any hotel, then it redirect to another endpoint, where i can modify the hotel). My idea was to create a class where I have the variable which can store the response.

export class Hotel {
data = {
    type: 'hotels',
    id: '',
    attributes: {
        location: '',
        name: '',
        main_image_src: '',
        has_wifi: '',
        has_parking: '',
        has_pets: '',
        has_restaurant: '',
        has_bar: '',
        has_swimming_pool: '',
        has_air_conditioning: '',
        has_gym: '',
        meal_plan: '',
        user_id: '',
        booking_id: '',
        amount: '',
        currency: '',
        status: '',
        stars: ''
    }
};

Then it is instantiated in a service:

@Injectable()
export class HotelService {
    hotel = new Hotel;
}

The service is imported in the hotelregister component and I save the response object there, like this:

 getHotelId(id) {
    const endpoint = 'https://cake-cup.glitch.me/api/hotels/'+id;
    this.hotelregistrationservice.httpRequest(this.hotelservice.hotel, 
    endpoint, 'get')
        .subscribe(
            response => {
                this.hotelservice.hotel.data = response;
                this.router.navigate(['hotels/1'])

            },
            error => {
                console.error(error)
            });
}

Here, if I console log the hotelservice.hotel.data, I have the correct response. This is what I am trying to use in the modifier component like this: import { HotelService } from '../hotel.service';

@Component({
  selector: 'app-single-hotel',
  templateUrl: './single-hotel.component.html',
  styleUrls: ['../../assets/app.component.scss'],
  providers: [HotelService]
})
export class SingleHotelComponent implements OnInit {

  constructor(
    public hotelservice: HotelService,
 ) {
    console.log(this.hotelservice.hotel.data)
   }

 ngOnInit(
  ) { }
 }

However, the hotelservice.hotel.data is undefined. Could you please help, to fix the issue?


Solution

  • The problem is that you should add your service in your core module eg. app.module.ts in the providers section. This way it will be a singleton, otherwise you are instantiating a new service in each component and each one will have its own independent data.

    Hope this makes sense, otherwise please let me know.

    Edit: You'll have to remove the HotelService from any other components' provider section