离子角不会发送标头

时间:2019-08-20 03:08:30

标签: javascript angular ionic-framework

我正在尝试使用API​​将数据存储在数据库中,并且出现Trying to get property 'id' of non-object错误。

我收到该错误的原因是因为Ionic不会将我的用户令牌发送到服务器

0: Closure (HttpHeaders)
  headers:
    Accept: "application/json, text/plain"
    Authorization: "undefined undefined"  <--- here
    Content-Type: "application/json"

代码

store.page.ts

此数据将发送到存储服务,然后从那里发送到服务器。

create() {
    const addToko = this.addToko.value;
    this.storeService.store(
      addToko.name,
      addToko.description,
      addToko.phone,
      addToko.province_id,
      addToko.kota_id,
      addToko.address,
      addToko.logo = this.logoURI,
      addToko.banner = this.bannerURI,
    ).subscribe(
      data => {
        this.alertService.presentToast(data);
        console.log('done ', data);
      },
      error => {
        this.alertService.presentToast(error);
        console.log('error ', error);
      }
    );
  }

store.service.ts

此处的数据将发送到服务器

export class StoreService {

  token: any; //setting user token

  constructor(
    private http: HttpClient,
    private env: EnvService,
    private storage: NativeStorage,
  ) {
   //gettinguser token
    this.storage.getItem('token').then(
      data => {
        this.token = data;
        console.log('token data', data);
      },
      error => {
        this.token = null;
      }
    );
  }

  store(
    name: String,
    description: String,
    phone: String,
    province_id: String,
    kota_id: String,
    address: String,
    logo: String,
    banner: String,
  ) {
    // adding headers to request
    const headers = new HttpHeaders({
      'Accept': 'application/json, text/plain',
      'Content-Type': 'application/json',
      'Authorization': this.token["token_type"] + " " + this.token["access_token"]
    });

    return this.http.post(this.env.STORES_URL,
      { name: name, description: description, phone: phone, province_id: province_id, kota_id: kota_id, address: address, logo: logo, banner: banner, headers: headers } // defining headers to request
    )
  }
}

可能会有所帮助:

我有Auth.service.ts负责用户登录状态和路由防护等。在那里,我有下面的功能可以获取用户令牌,并且在那里工作正常,我在store.service.ts (code above)中实现了相同的功能但这不起作用。

getToken() {
    return this.storage.getItem('token').then(
      data => {
        this.token = data;
        if (this.token != null) {
          this.isLoggedIn = true;
        } else {
          this.isLoggedIn = false;
        }
      },
      error => {
        this.token = null;
        this.isLoggedIn = false;
      }
    );
  }

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您对store服务的实现需要更正。 您已将headers包含在对象主体中,然后从其中取出。

    return this.http.post(this.env.STORES_URL,
           { name: name, description: description, phone: phone, province_id: 
             province_id, kota_id: kota_id, address: address, logo: logo, 
             banner: banner, headers: headers /* headers should not be embedded in object body*/
           });

    return this.http.post(this.env.STORES_URL,
           { name: name, description: description, phone: phone, province_id: 
             province_id, kota_id: kota_id, address: address, logo: logo, 
             banner: banner
           }, {headers: headers});

答案 1 :(得分:0)

这可能是竞争条件,在发出请求之前尚未设置令牌。您可以设置 http-interceptor 来为请求设置auth标头:

INSERT INTO .inner.shared.aggregated_calls_1h
SELECT 
  client_id,
  toUInt64(floor(t / (60000 * 60)) * (60000 *60)) AS t,
  ...

将拦截器添加到app.module中的import { Injectable } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http'; import { Observable } from 'rxjs'; import { of, from} from 'rxjs'; import { switchMap, tap } from 'rxjs/operators'; @Injectable() export class NoopInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // convert promise to observable // fetch token and switch to inner observable where we add headers return from(this.storage.getItem('token')).pipe( switchMap((token) => { // clone request and add headers const authReq = req.clone({ headers: new HttpHeaders({ 'Authorization': token["token_type"] + " " + token["access_token"] }) }) return next.handle(authReq); }) ) } 数组中:

providers

然后只需从您的请求中删除{ provide: HTTP_INTERCEPTORS, useClass: NoopInterceptor, multi: true }, (就像在其他答案中的错误位置一样):

httpOptions