ionic4——请求数据

【一】请求数据

1、在终端

ionic g service services/httpservice

2、app.module.ts

ionic4——请求数据_第1张图片

3、httpservice.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
	providedIn: 'root'
})
export class HttpserviceService {
	constructor(public http: HttpClient) { }
	get(api) {
		return new Promise((resolve, reject) => {
			this.http.get(api).subscribe((response) => {
				resolve(response);
			}, (err) => {
				reject(err);
			});
		});
	}
}

4、页面.ts

import { Component, OnInit } from '@angular/core';
import { HttpserviceService} from '../services/httpservice.service';

@Component({
selector: 'app-tab4',
templateUrl: './tab4.page.html',
styleUrls: ['./tab4.page.scss'],
})

export class Tab4Page implements OnInit {
	public list: any[] = [];
	constructor(public httpService: HttpserviceService) { }
	ngOnInit() {
		this.getData();
	}
	getData() {
		const api = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1';
		this.httpService.get(api).then((response: any) => {
			console.log(response);
			this.list = response.result;
		});
	}
}

5、页面.html


    
        
            {{item.title}}
        
    

【上拉加载】

1、页面.html


    
    

2、页面.ts

import { Component, OnInit } from '@angular/core';
import { HttpserviceService} from '../services/httpservice.service';

@Component({
selector: 'app-tab4',
templateUrl: './tab4.page.html',
styleUrls: ['./tab4.page.scss'],
})

export class Tab4Page implements OnInit {
    public list: any[] = [];
    public page: any = 1;
    // public hasMore = true;

    constructor(public httpService: HttpserviceService) { }

    ngOnInit() {
        this.getData();
    }

    getData() {
        const api = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=' + this.page;
        this.httpService.get(api).then((response: any) => {
        console.log(response);
        this.list = response.result;
        ++this.page;
        });
    }

    // 上拉加载数据
    loadMore(e) {
        const api = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=' + this.page;
        this.httpService.get(api).then((response: any) => {
            console.log(response);
            this.list = this.list.concat( response.result);
            ++this.page;
            // 判断下一页有没有数据
            if (response.result.length < 20) {
                e.target.disabled = true;
                // 或者
                // this.hasMore = false;
            }
            e.target.comlete();
        });
    }
}

 

你可能感兴趣的:(前端)