0

I have this http.get request but it is being triggered twice. It is within my constructor.

import { Component } from '@angular/core';
import { NavController, LoadingController } from 'ionic-angular';
import { Auth, User, IDetailedError } from '@ionic/cloud-angular';
import { Http, URLSearchParams, Headers } from "@angular/http"
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/share';

import { DetailsPage } from '../details/details';
import { LoginPage } from '../login/login';

@Component({
  selector: 'page-dashboard',
  templateUrl: 'dashboard.html'
})
export class Dashboard {

  visitors: any;
  currentSite: any;
  searchDate: String = new Date().toISOString();

  constructor(public navCtrl: NavController, public http: Http, public loadingCtrl: LoadingController, public user: User, public auth: Auth) {

    if (this.auth.isAuthenticated()) {

        this.currentSite = this.user.get('siteName',0);

        let loading = this.loadingCtrl.create({
          spinner: 'bubbles',
          content: 'Fetching visitors ...',
          duration: 5000
        });

        loading.present();  

        var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');  
        headers.append('Authorization', 'Basic '+ btoa(this.user.get('siteID',0)+':'+this.user.get('token',0)));      

        this.http.get('http://api.domain.com/visitors?search_from='+this.searchDate+'&search_to='+this.searchDate, {headers:headers}).map(res => res.json()).share().subscribe(data => {
            this.visitors = data.res;
            loading.dismiss();
        });   

    } else {
        this.navCtrl.setRoot(LoginPage);
    }

  }

Based on Angular2 http.post gets executed twice it looks like I need to include share() but when I try this I get an error ..

If I put share() at the end then I get "Property does not exist on type Subscription" and if I put it before subscribe then I get "Property share does not exist on type observable"

Can somebody tell me where share() should go ... or whether I actually have a different issue?

Community
  • 1
  • 1
Chris
  • 4,672
  • 13
  • 52
  • 93
  • put share after map `.map(res => res.json()).share().subs...` – El houcine bougarfaoui Mar 07 '17 at 23:05
  • That gives me .... Property share does not exist on type observable – Chris Mar 07 '17 at 23:06
  • I think you have a different issue. Does your Request URL look OK? Is your authorization header set correctly? Try adding console.log to your constructor to see if constructor isn't executed twice. – Adnan A. Mar 07 '17 at 23:08
  • import this : `import 'rxjs/add/operator/share';` – El houcine bougarfaoui Mar 07 '17 at 23:10
  • How do you know it's being called twice? – MikeOne Mar 07 '17 at 23:11
  • @BougarfaouiElhoucine adding the import line means that I no longer get the error (good!) but the call is still being triggered twice – Chris Mar 07 '17 at 23:11
  • @AdnanA. yep, done this, the constructor is only being called once – Chris Mar 07 '17 at 23:12
  • @MikeOne I also control the API so I can see two requests coming in. Actually, looking at this more closely I can see that I receive an OPTIONS request and then a GET request. The OPTIONS request doesn't include the auth header whereas the GET does – Chris Mar 07 '17 at 23:13
  • can you put more code so we can see where is the probelm – El houcine bougarfaoui Mar 07 '17 at 23:13
  • That is what I thought. You're doing a CORS request, the OPTIONS call is the preflight. Perfectly normal. – MikeOne Mar 07 '17 at 23:14
  • @MikeOne Yep, OK, so my API returns back nothing for the OPTIONS request but returns JSON for the GET request. The actual problem I am having is that I am not seeing my results in the template. Seems like it's getting the response from OPTIONS and then stopping there. Badly explained, sorry, – Chris Mar 07 '17 at 23:16
  • Btw, you should probably not do that work in your component's constructor either. You should move all that constructor code into an ngOnInit method – snorkpete Mar 07 '17 at 23:18
  • The OPTIONS response should be ignored by the subscribe so you're having another issue I think – MikeOne Mar 07 '17 at 23:19
  • Are you seeing an error in the browser with the request? if your API isn't set up correctly to support CORS, the browser won't allow the response through – snorkpete Mar 07 '17 at 23:21
  • OK - sorted. You've all been helpful and helped me learn something new, realise that then OPTIONS request isn't a problem and also made me discover some muppetry in my API (basically this was my fault). Thank you for the advice @Snorkpete – Chris Mar 07 '17 at 23:22
  • I'll credit myself then :-) – MikeOne Mar 07 '17 at 23:24

1 Answers1

3

You mentioned the OPTIONS request. Are you running the angular 2 site from a different server than your API?

If so, then you'll have to deal with CORS - i.e. the browser will send a first OPTIONS request and check the headers of the response to see if CORS is permitted.

That would explain why you see two requests on your back end API

snorkpete
  • 14,278
  • 3
  • 40
  • 57