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>
界面效果: