在第一个http get请求

时间:2017-07-26 06:51:16

标签: angular ionic2 angular-http

我希望每次请求都传递查询字符串api_toke = {{tokenStored}}。下面的代码是我用来实现它的。问题是,当最初调用页面时,令牌未定义,但之后它按预期工作。我该如何解决这个问题?

这是控制台中抛出的错误

polyfills.js:3 GET http://myapp.dev/app/public/api/project?api_token=undefined 401 (Unauthorized)

list-projects.ts:39 Response {_body: "{"error":"Unauthenticated."}", status: 401, ok: false, statusText: "Unauthorized", headers: Headers…} "Error Caught

组件

export class ListProjectsPage {

   ionViewDidLoad() {
      this.http.get(this.config.url.api+this.config.endpoint.listprojects)
        .subscribe(
      data => {
        this.projects = data.json();
      },
      error => {
        console.log(error,"Error");
      });
  }

}

我的自定义HTTP提供程序

import { Injectable } from '@angular/core';
import { Http, RequestOptions, URLSearchParams } from '@angular/http';
import * as AppConfig from '../../app/app.config';
import {Storage} from '@ionic/storage';

@Injectable()
export class HttpProvider {

  config: any;
  token: any;
  constructor(public http: Http,public storage: Storage) {
    this.config = AppConfig.config;
    this.storage.get('token').then(token => {
      this.token = token;
    }).catch(e => {
      this.token = null;
    });
  }

  get(url:string){
    return this.http.get(url+'?api_token='+this.token);
  }

}

2 个答案:

答案 0 :(得分:0)

我建议你:

1-确保令牌位于localstorage中且密钥为'token': - )

2 - 也许使用Angular2 / 4和Ionic 2/3应用程序的插件来完成Angularjs和Ionic 1 http拦截器的等效...我可以向你推荐这个(我用这个):angular2-http-interceptorhttps://www.npmjs.com/package/angular2-http-interceptor

然后你可以这样做:

a)为后端的令牌响应创建一个模型,如:

export class Auth {
    public access_token: string;
    public userName: string;

}

b)创建一个服务(没有@inject()装饰),如:

import { Request, Response } from '@angular/http';
import { IHttpInterceptor } from 'angular2-http-interceptor';
import { Auth } from '../models/index';


export class AuthInterceptor implements IHttpInterceptor {
    constructor() {

    }

    before(request: Request): Request {
        if (localStorage && localStorage.length > 0 && localStorage.getItem("AuthData")) {

            var auth = JSON.parse(localStorage.getItem("token")) as Auth;
            if (!auth || !auth.access_token) return request;

            request.headers.set("Authorization", "Bearer " + auth.access_token)
        }
        return request;
    }


}

c)你的app.module使用如下:

 HttpInterceptorModule.withInterceptors([{
            deps: [],
            provide: HttpInterceptor,
            useClass: AuthInterceptor,
            multi: true
        }])

现在每次执行http请求时,它会自动检查您是否拥有令牌并将其注入请求的标题中。希望它对您有所帮助! ...

N.B如果您需要在传递令牌时更改方式(可能在查询字符串中而不是在请求的标题中),您可以更改B)点并反映所有请求

答案 1 :(得分:0)

undefined因为get方法在storage解析承诺并为“令牌”赋值之前调用import { Injectable } from '@angular/core'; import { Http, RequestOptions, URLSearchParams } from '@angular/http'; import * as AppConfig from '../../app/app.config'; import {Storage} from '@ionic/storage'; @Injectable() export class HttpProvider { config: any; token: any; constructor(public http: Http,public storage: Storage) { this.config = AppConfig.config; } get(url:string){ this.storage.get('token').then(token => { return this.http.get(url+'?api_token='+this.token); }) } } 方法。{/ 1>

config

虽然这也可以,但最好在应用程序启动时在提供程序(http中)存储令牌,并在进行#include <stdio.h> int main(void) { const char *a = "abcdefg"; const char *b = "xyz"; while(*a || *b){ if(*a) putchar(*a++); if(*b) putchar(*b++); } } 调用时使用已定义的令牌。