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
1 import { Injectable } from '@angular/core'; 2 import { Observable } from 'rxjs'; 3 @Injectable({ 4 providedIn: 'root' 5 }) 6 export class RequestService { 7 8 constructor() { } 9 10 //同步方式 11 getData() { 12 alert("我是服务方法"); 13 } 14 15 //回调方式 16 getCallbackData(cb) { 17 setTimeout(() => { 18 19 var username = 'xiao ming--callback'; 20 // return data; 21 cb(username); 22 }, 1000); 23 } 24 25 //promise 26 getPromiseData(){ 27 28 return new Promise((resolve,reject)=>{ 29 30 setTimeout(() => { 31 var username = 'xiao ming--promise'; 32 resolve(username); 33 }, 1000); 34 }); 35 } 36 37 //rxjs 38 getRxjsData(){ 39 40 return new Observable((obj)=>{ 41 42 setTimeout(() => { 43 var username="xiao hong -- rxjs"; 44 obj.next(username); 45 }, 3000); 46 47 }); 48 } 49 }
home.component.ts
1 import { Component, OnInit} from '@angular/core'; 2 import { RequestService } from '../../services/request.service'; 3 @Component({ 4 selector: 'app-home', 5 templateUrl: './home.component.html', 6 styleUrls: ['./home.component.css'] 7 }) 8 export class HomeComponent implements OnInit { 9 10 constructor(public req: RequestService) { } 11 12 ngOnInit() { 13 } 14 15 getServiceMethod() { 16 this.req.getData(); 17 } 18 19 20 //回调 获取异步数据 21 getAsyncMethod() { 22 this.req.getCallbackData((uname) => { 23 alert(uname); 24 }) 25 } 26 27 //promise获取异步数据 28 getPromiseMethod() { 29 var pro = this.req.getPromiseData(); 30 pro.then((data) => { 31 alert(data); 32 }); 33 } 34 35 //rxjs获取异步数据 36 getRxjsMethod() { 37 38 var rxjsdata = this.req.getRxjsData(); 39 var start = rxjsdata.subscribe((data) => { 40 alert(data); 41 }); 42 43 44 } 45 46 47 removeRxjsMethod() { 48 49 var rxjsdata = this.req.getRxjsData(); 50 var start = rxjsdata.subscribe((data) => { 51 alert(data); 52 }); 53 54 setTimeout(() => { 55 start.unsubscribe();//取消订阅:由于上面方法执行3s中,在1s后,就取消了该请求 56 }, 1000); 57 } 58 59 }
home.component.html
1 <button (click)="getServiceMethod()">我可以调用服务里面的方法哦(同步)</button> 2 <br> 3 4 <button (click)="getAsyncMethod()">我可以调用服务里面的方法哦(异步-callback)</button> 5 <br> 6 7 <button (click)="getPromiseMethod()">我可以调用服务里面的方法哦(异步-promise)</button> 8 <br> 9 <button (click)="getRxjsMethod()">我可以调用服务里面的方法哦(异步-rxjs)</button> 10 <br> 11 <button (click)="getRxjsMethod()">我可以调用服务里面的方法哦(rxjs,取消订阅)</button> 12 <p>home works!</p> 13 <hr>
界面效果: