Angular学习系列八:调用服务方法
1:创建服务:ng g service services/request
2:使用rxjs就需要在service 中引用: import { Observable } from ‘rxjs‘;
3:在组件中引用服务:
import { RequestService } from ‘../../services/request.service‘;
constructor(public req: RequestService)
4:学习目标:调用服务方法,使用回调方法获取服务方法,使用异步promise获取,使用rxjs异步获取数据
request.service.ts
import { Injectable } from ‘@angular/core‘; import { Observable } from ‘rxjs‘; @Injectable({ providedIn: ‘root‘ }) export class RequestService { constructor() { } //同步方式 getData() { alert("我是服务方法"); } //回调方式 getCallbackData(cb) { setTimeout(() => { var username = ‘xiao ming--callback‘; // return data; cb(username); }, 1000); } //promise getPromiseData(){ return new Promise((resolve,reject)=>{ setTimeout(() => { var username = ‘xiao ming--promise‘; resolve(username); }, 1000); }); } //rxjs getRxjsData(){ return new Observable((obj)=>{ setTimeout(() => { var username="xiao hong -- rxjs"; obj.next(username); }, 3000); }); } }
home.component.ts
import { Component, OnInit} from ‘@angular/core‘; import { RequestService } from ‘../../services/request.service‘; @Component({ selector: ‘app-home‘, templateUrl: ‘./home.component.html‘, styleUrls: [‘./home.component.css‘] }) export class HomeComponent implements OnInit { constructor(public req: RequestService) { } ngOnInit() { } getServiceMethod() { this.req.getData(); } //回调 获取异步数据 getAsyncMethod() { this.req.getCallbackData((uname) => { alert(uname); }) } //promise获取异步数据 getPromiseMethod() { var pro = this.req.getPromiseData(); pro.then((data) => { alert(data); }); } //rxjs获取异步数据 getRxjsMethod() { var rxjsdata = this.req.getRxjsData(); var start = rxjsdata.subscribe((data) => { alert(data); }); } removeRxjsMethod() { var rxjsdata = this.req.getRxjsData(); var start = rxjsdata.subscribe((data) => { alert(data); }); setTimeout(() => { start.unsubscribe();//取消订阅:由于上面方法执行3s中,在1s后,就取消了该请求 }, 1000); } }
home.component.html
<button (click)="getServiceMethod()">我可以调用服务里面的方法哦(同步)</button> <br> <button (click)="getAsyncMethod()">我可以调用服务里面的方法哦(异步-callback)</button> <br> <button (click)="getPromiseMethod()">我可以调用服务里面的方法哦(异步-promise)</button> <br> <button (click)="getRxjsMethod()">我可以调用服务里面的方法哦(异步-rxjs)</button> <br> <button (click)="getRxjsMethod()">我可以调用服务里面的方法哦(rxjs,取消订阅)</button> <p>home works!</p> <hr>
界面效果:
相关推荐
dynsxyc 2020-01-03
wcsandlili 2019-10-22
QiaoranC 2020-09-25
颤抖吧腿子 2020-09-04
liduote 2020-06-16
阿斌Elements 2020-06-11
xxuncle 2020-06-05
ChinaGuanq 2020-06-05
wanghongsha 2020-03-26
csm0 2020-03-05
shyoushine 2020-02-25
electronvolt 2020-02-12
jsonwoo 2020-01-20
wwwxuewen 2020-01-04
liangjielaoshi 2019-12-27
bowean 2019-12-27
wwwxuewen 2019-12-25
liwusen 2019-12-16
颤抖吧腿子 2019-12-16