Angular怎么利用service实现自定义服务(angular,service,web开发)

时间:2024-04-28 22:48:10 作者 : 石家庄SEO 分类 : web开发
  • TAG :

Angular怎么利用service实现自定义服务

添加服务

我们在 app/services 中添加 notification.service.ts 服务文件(请使用命令行生成),添加相关的内容:

//notification.service.tsimport{Injectable}from'@angular/core';import{Observable,Subject}from'rxjs';//通知状态的枚举exportenumNotificationStatus{Process="progress",Success="success",Failure="failure",Ended="ended"}@Injectable({providedIn:'root'})exportclassNotificationService{privatenotify:Subject<NotificationStatus>=newSubject();publicmessageObj:any={primary:'',secondary:''}//转换成可观察体publicgetNotification():Observable<NotificationStatus>{returnthis.notify.asObservable();}//进行中通知publicshowProcessNotification(){this.notify.next(NotificationStatus.Process)}//成功通知publicshowSuccessNotification(){this.notify.next(NotificationStatus.Success)}//结束通知publicshowEndedNotification(){this.notify.next(NotificationStatus.Ended)}//更改信息publicchangePrimarySecondary(primary?:string,secondary?:string){this.messageObj.primary=primary;this.messageObj.secondary=secondary}constructor(){}}

是不是很容易理解...

我们将 notify 变成可观察物体,之后发布各种状态的信息。

创建组件

我们在 app/components 这个存放公共组件的地方新建 notification 组件。所以你会得到下面的结构:

notification├──notification.component.html//页面骨架├──notification.component.scss//页面独有样式├──notification.component.spec.ts//测试文件└──notification.component.ts//javascript文件

我们定义 notification 的骨架:

<!--notification.component.html--><!--支持手动关闭通知--><button(click)="closeNotification()">关闭</button><h2>提醒的内容:{{message}}</h2><!--自定义重点通知信息--><p>{{primaryMessage}}</p><!--自定义次要通知信息--><p>{{secondaryMessage}}</p>

接着,我们简单修饰下骨架,添加下面的样式:

//notification.component.scss:host{position:fixed;top:-100%;right:20px;background-color:#999;border:1pxsolid#333;border-radius:10px;width:400px;height:180px;padding:10px;//注意这里的active的内容,在出现通知的时候才有&.active{top:10px;}&.success{}&.progress{}&.failure{}&.ended{}}

success, progress, failure, ended 这四个类名对应 notification service 定义的枚举,可以按照自己的喜好添加相关的样式。

最后,我们添加行为 javascript 代码。

//notification.component.tsimport{Component,OnInit,HostBinding,OnDestroy}from'@angular/core';//新的知识点rxjsimport{Subscription}from'rxjs';import{debounceTime}from'rxjs/operators';//引入相关的服务import{NotificationStatus,NotificationService}from'src/app/services/notification.service';@Component({selector:'app-notification',templateUrl:'./notification.component.html',styleUrls:['./notification.component.scss']})exportclassNotificationComponentimplementsOnInit,OnDestroy{//防抖时间,只读privatereadonlyNOTIFICATION_DEBOUNCE_TIME_MS=200;protectednotificationSubscription!:Subscription;privatetimer:any=null;publicmessage:string=''//notificationservice枚举信息的映射privatereflectObj:any={progress:"进行中",success:"成功",failure:"失败",ended:"结束"}@HostBinding('class')notificationCssClass='';publicprimaryMessage!:string;publicsecondaryMessage!:string;constructor(privatenotificationService:NotificationService){}ngOnInit():void{this.init()}publicinit(){//添加相关的订阅信息this.notificationSubscription=this.notificationService.getNotification().pipe(debounceTime(this.NOTIFICATION_DEBOUNCE_TIME_MS)).subscribe((notificationStatus:NotificationStatus)=>{if(notificationStatus){this.resetTimeout();//添加相关的样式this.notificationCssClass=`active${notificationStatus}`this.message=this.reflectObj[notificationStatus]//获取自定义首要信息this.primaryMessage=this.notificationService.messageObj.primary;//获取自定义次要信息this.secondaryMessage=this.notificationService.messageObj.secondary;if(notificationStatus===NotificationStatus.Process){this.resetTimeout()this.timer=setTimeout(()=>{this.resetView()},1000)}else{this.resetTimeout();this.timer=setTimeout(()=>{this.notificationCssClass=''this.resetView()},2000)}}})}privateresetView():void{this.message=''}//关闭定时器privateresetTimeout():void{if(this.timer){clearTimeout(this.timer)}}//关闭通知publiccloseNotification(){this.notificationCssClass=''this.resetTimeout()}//组件销毁ngOnDestroy():void{this.resetTimeout();//取消所有的订阅消息this.notificationSubscription.unsubscribe()}}

在这里,我们引入了 rxjs 这个知识点,RxJS 是使用 Observables 的响应式编程的库,它使编写异步或基于回调的代码更容易。这是一个很棒的库,接下来的很多文章你会接触到它更多的内容。

这里我们使用了 debounce 防抖函数,函数防抖,就是指触发事件后,在 n 秒后只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数的执行时间。简单来说:当一个动作连续触发,只执行最后一次。

ps: throttle 节流函数:限制一个函数在一定时间内只能执行一次

在面试的时候,面试官很喜欢问...

调用

因为这个一个全局的服务,我们在 app.component.html 中调用此组件:

//app.component.html<router-outlet></router-outlet><app-notification></app-notification>

为了方便演示,我们在 user-list.component.html 中添加按钮,方便触发演示:

//user-list.component.html<button(click)="showNotification()">clickshownotification</button>

触发相关的代码:

//user-list.component.tsimport{NotificationService}from'src/app/services/notification.service';//...constructor(privatenotificationService:NotificationService){}//展示通知showNotification():void{this.notificationService.changePrimarySecondary('主要信息1');this.notificationService.showProcessNotification();setTimeout(()=>{this.notificationService.changePrimarySecondary('主要信息2','次要信息2');this.notificationService.showSuccessNotification();},1000)}
 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:Angular怎么利用service实现自定义服务的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:jquery中的fadeout方法如何用下一篇:

7 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18