在加载数据之前在视图中加载数据

时间:2016-06-08 14:42:35

标签: ionic-framework angular ionic2

我有一个问题,我正在使用Ionic 2和angular 2。

我必须在视图中显示一些数据,但是我从同一页面中的API获取这些数据,所以当我尝试在视图中显示它们时,它们尚未定义。获取这些数据后,如何等待加载视图?

我试过onPageWillEnter但它不起作用。

提前谢谢。

2 个答案:

答案 0 :(得分:15)

您可以使用*ngIf

打包模板
template: `
 <div *ngIf="data">
   ... <!-- content -->
 </div>`

设置data后,将显示内容。

您还可以使用安全导航或Elvis运算符来避免错误消息

template: `<div>{{data?.someProp}}</div>`

以避免在datanull

时出现错误消息

答案 1 :(得分:1)

提供程序允许您从服务器获取数据 生成: <?php require 'vendor/autoload.php'; # Replace these values. You probably want to start with your Sandbox credentials # to start: https://docs.connect.squareup.com/articles/using-sandbox/ # The ID of the business location to associate processed payments with. # If you're testing things out, use a sandbox location ID. # # See [Retrieve your business's locations](https://docs.connect.squareup.com/articles/getting-started/#retrievemerchantprofile) # for an easy way to get your business's location IDs. $location_id = 'xxxxxxxxxx'; //for public posting purposes # The access token to use in all Connect API requests. Use your *sandbox* access # token if you're just testing things out. $access_token = 'xxxxxxxxx'; //for public posting purposes # Helps ensure this code has been reached via form submission if ($_SERVER['REQUEST_METHOD'] != 'POST') { error_log("Received a non-POST request"); echo "Request not allowed"; http_response_code(405); return; } # Fail if the card form didn't send a value for `nonce` to the server $nonce = $_POST['nonce']; if (is_null($nonce)) { echo "Invalid card data"; http_response_code(422); return; } $transaction_api = new \SquareConnect\Api\TransactionApi(); $request_body = array ( "card_nonce" => $nonce, # Monetary amounts are specified in the smallest unit of the applicable currency. # This amount is in cents. It's also hard-coded for $1.00, which isn't very useful. "amount_money" => array ( "amount" => 100, "currency" => "CAD" ), # Every payment you process with the SDK must have a unique idempotency key. # If you're unsure whether a particular payment succeeded, you can reattempt # it with the same idempotency key without worrying about double charging # the buyer. "idempotency_key" => uniqid() ); # The SDK throws an exception if a Connect endpoint responds with anything besides # a 200-level HTTP code. This block catches any exceptions that occur from the request. try { $result = $transaction_api->charge($access_token, $location_id, $request_body); echo "<pre>"; print_r($result); echo "</pre>"; } catch (\SquareConnect\ApiException $e) { echo "Caught exception!<br/>"; print_r("<strong>Response body:</strong><br/>"); echo "<pre>"; var_dump($e->getResponseBody()); echo "</pre>"; echo "<br/><strong>Response headers:</strong><br/>"; echo "<pre>"; var_dump($e->getResponseHeaders()); echo "</pre>"; }

ionic generate provider MyProvider --ts

menu.ts

@Injectable()
export class MenuProvider {
    data: any = null;

    constructor(public http: Http) { }

    load() {
        if (this.data) {
            // already loaded data
            return Promise.resolve(this.data);
        }

        // don't have the data yet
        return new Promise(resolve => {
            // We're using Angular Http provider to request the data,
            // then on the response it'll map the JSON data to a parsed JS object.
            // Next we process the data and resolve the promise with the new data.
            this.http.get('asset/menu.json')
                .map(res => res.json())
                .subscribe(data => {
                    // we've got back the raw data, now generate the core schedule data
                    // and save the data for later reference
                    this.data = data;
                    resolve(this.data);
                });
        });
    }
}

之后使用带有ngFor,ngIf ....的temple来显示

import {MenuProvider} from "../../providers/menu-provider/menu-provider";
import {Component, OnInit} from '@angular/core';
import {IONIC_DIRECTIVES, NavController, Modal} from 'ionic-angular';
import {AccountHistoryPage} from "../../pages/account-history/account-history";

/*
  Generated class for the MenuComponent component.

  See https://angular.io/docs/ts/latest/api/core/ComponentMetadata-class.html
  for more info on Angular 2 Components.
*/
@Component({
    selector: 'menu-component',
    templateUrl: 'build/components/menu-component/menu-component.html',
    directives: IONIC_DIRECTIVES,
    providers: [MenuProvider]
})
export class MenuComponent {
    // menu object
    jsonMenu: any;
    constructor(public nav: NavController, menuProvider: MenuProvider) {

        // TODO: show progress
        menuProvider.load().then(data => {
            // TODO: turn off menu load json progress

            // data after proccessed.
            this.jsonMenu = data;
            console.log(this.jsonMenu);
        }, err => console.log(err));
    }

    itemClick(moduleNumber: number) {
        console.log(moduleNumber);

        let page: any = null;
        if (moduleNumber == 210102) {
            page = Modal.create(AccountSourcePage);
        }

        if (moduleNumber == 210103) {
            page = Modal.create(AccountBeneficiatyPage);
        }

        if (moduleNumber == 210101) {
            page = Modal.create(AccountHistoryPage);
        }
        this.nav.present(page);
    }
}