http.get被两次调用 [英] http.get being called twice

查看:182
本文介绍了http.get被两次调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

  }

基于 Angular2 http.post被执行两次需要包括share(),但是当我尝试这个时,我得到一个错误..

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 ..

如果将share()放在末尾,则会显示订阅类型上不存在该属性",如果在订阅前放置该属性,则会得到可观察类型上不存在属性共享"

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"

有人可以告诉我share()应该去哪里……或者我实际上是否有其他问题?

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

推荐答案

您提到了OPTIONS请求.您是否正在从与API不同的服务器上运行angular 2网站?

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

如果是这样,则您必须处理CORS-即浏览器将发送第一个OPTIONS请求,并检查响应的标头以查看是否允许CORS.

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.

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

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

这篇关于http.get被两次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆