http.get被调用两次

时间:2017-03-07 22:51:39

标签: angular

我有这个http.get请求,但它被触发了两次。它在我的构造函数中。

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);
    }

  }

基于Angular2 http.post gets executed twice看起来我需要包含share()但是当我尝试这个时我得到一个错误..

如果我将share()放在最后,那么我得到“属性在订阅类型上不存在”,如果我在订阅之前将其放入,那么我得到“属性共享在类型observable上不存在”

有人可以告诉我share()应该去哪里......或者我是否真的有不同的问题?

1 个答案:

答案 0 :(得分:3)

您提到了OPTIONS请求。您是否从与API不同的服务器上运行角度2站点?

如果是这样,那么你将不得不处理CORS - 即浏览器将发送第一个OPTIONS请求并检查响应的标头以查看是否允许CORS。

这可以解释为什么您在后端API上看到两个请求