【问题标题】:HTTP works in web but not working in actual android device ( IONIC mobile development )HTTP 在 web 中有效,但在实际的 android 设备中无效(IONIC 移动开发)
【发布时间】:2020-06-13 19:16:36
【问题描述】:

问题:我的 ngfor 在运行网络时运行良好,但是当我在真实设备上模拟我的应用程序时,它就无法正常工作。我看遍了 互联网上的解决方案,但找不到,就像一个接近的一样(多数民众赞成在 我怎么想),有人说这是 ngZone 问题,我没有 知道它是什么。

我的服务

getMenuObject(): Observable<any> {

    return this.http
      .post("xxxxxxx.xxxxxxxxx.xxxxxxxxx.xxxxxxxxxxx",{ HotelId:25, GroupId:9 });
  }

我的 .ts

data: Array<any>=[]

ngOnInit(){
 this.httpService.getMenuObject().toPromise().then(x=>{
      this.data = x;
      console.log(this.data)
      if(x.IsGroup==true){
          this.splashScreen.hide();

       } else{
         this.router.navigate(['folder/Inbox']);
       }
    });
}

我的html:

<ion-card  *ngFor="let otel of data.MobileHotelDefinitions" style="margin: 40px 0;border-radius: 0;">
        <ion-card-header style="padding: 0;">
          <ion-img (click)="goToHotel()" [src]="otel.MobileApplicationDefinition.GroupImageUrl"></ion-img>
          <div class="otelName">
            <div style="flex: 1;">{{otel.Name}}</div>
            <div style="color: goldenrod;">★★★★★</div>
          </div>
        </ion-card-header>
        <ion-card-content>
          Keep close to Nature's heart... and break clear away, once in awhile,
          and climb a mountain or spend a week in the woods. Wash your spirit clean.
        </ion-card-content>
      </ion-card>

我的控制台:

我在网络浏览器上的应用(ionic serve --o):

我在真正的 android 设备(华为 android 9)上的应用程序:

【问题讨论】:

  • 尝试用 NgZone 封装你的代码并检查。

标签: android angular ionic-framework ngfor


【解决方案1】:
  1. data 变量不是数组。其中的MobileHotelDefinitions 属性是数组。所以最好将其类型定义为any 而不是Array。
  2. 是否需要将 HTTP observable 转换为 Promise?尝试直接使用 observable。
  3. 在使用属性之前在模板中包含*ngIf 签入。
  4. 注意模板中safe navigation operator ?. 的使用。它会在尝试访问其子属性之前检查父属性是否已定义。

控制器

data: any;    // <-- `any` here

ngOnInit() {
  this.httpService.getMenuObject().subscribe(
    response => {
      this.data = response;
      console.log(this.data);
      if (response.IsGroup == true) {
        this.splashScreen.hide();
      } else {
        this.router.navigate(['folder/Inbox']);
      }
    },
    error => {
      // always good practice to handle HTTP errors
    }
  );
}

模板

<ng-container *ngIf="data">     <!-- check here -->
  <ion-card  *ngFor="let otel of data.MobileHotelDefinitions" style="margin: 40px 0;border-radius: 0;">
    <ion-card-header style="padding: 0;">
      <ion-img (click)="goToHotel()" [src]="otel?.MobileApplicationDefinition?.GroupImageUrl"></ion-img>
      <div class="otelName">
        <div style="flex: 1;">{{otel?.Name}}</div>
        <div style="color: goldenrod;">★★★★★</div>
      </div>
    </ion-card-header>
    <ion-card-content>
      Keep close to Nature's heart... and break clear away, once in awhile,
      and climb a mountain or spend a week in the woods. Wash your spirit clean.
    </ion-card-content>
  </ion-card>
</ng-container>

如果问题仍然存在,则变量更新位于 Angular 区域之外。尝试将调用包装在 NgZone.run() 函数中以在 Angular 区域内运行语句。

import { Component, NgZone, OnInit } from '@angular/core';

export class AppComponent implements OnInit {
  data: any;

  constructor(private zone:NgZone) { }

  ngOnInit() {
    this.httpService.getMenuObject().subscribe(
      response => {
        this.zone.run(() => this.data = response);    // <-- assign the value within Angular zone and trigger change detection
        console.log(this.data)
        if (response.IsGroup == true) {
          this.splashScreen.hide();
        } else {
          this.router.navigate(['folder/Inbox']);
        }
      },
      error => {
        // always good practice to handle HTTP errors
      }
    );
  }

【讨论】:

  • 我很遗憾地说以上都不起作用。你解释得很好,至少非常感谢你。这个问题真的很有趣,不是吗..
  • @WorldOfEmre:这很不幸。您能否检查后端是否发送了正确的响应?尝试在错误回调中做一些明显的事情,比如重定向到其他路线。这样我们就可以确保后端确实在移动设备中正确发送数据。
【解决方案2】:

我的问题是我尝试使用 httpClient(angular one),但在移动设备上你需要 ionic http,所以有 2 个 http:

  1. 从 '@ionic-native/http/ngx' 导入 { HTTP }; //移动端http 请求你必须使用这个 (you can install it from here)
  2. 从“@angular/common/http”导入 { HttpClient }; //对于浏览器 开发你必须使用这个。

而且很难为移动设备实现正确的 http 方式,为了帮助您,我在这里留下了一个示例移动 http 请求。 (以防止出现几个 http 错误)

我的服务.ts

 constructor(private http:HTTP, private httpWEB: HttpClient) {

    this.http.setHeader('*', 'Access-Control-Allow-Origin' , '*');
    this.http.setHeader('*', 'Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
    this.http.setHeader('*', 'Accept','application/json');
    this.http.setHeader('*', 'content-type','application/json');
    this.http.setDataSerializer('json');
  }

  post(url:string,body:any):Promise<any>{    
    return new Promise((resolve, reject) => {
      this.http.setDataSerializer('json');
      this.http.post(url, body, {}).then(res =>{
        resolve(JSON.parse(res.data));
      })
      .catch(err =>{
        reject(err);
      });
    });
  }

在 Config.xlm 中更新此部分以防止 http 请求出现 clearTextTraffic 错误

<edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
            <application android:networkSecurityConfig="@xml/network_security_config" />
            <application android:usesCleartextTraffic="true" />
        </edit-config>

同时更新您的 network_securty_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
        <domain includeSubdomains="true">testapi.xxx.com</domain>
    </domain-config>
</network-security-config>

【讨论】:

    猜你喜欢
    • 2016-12-10
    • 1970-01-01
    • 2019-09-11
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多