Angular:HTTP

HTTP概览

在这里插入图片描述

HTTP消息

在这里插入图片描述

Restful API

在这里插入图片描述

Angular HttpClient

在这里插入图片描述
src\app\home\services\home.service.ts:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Channel, ImageSlider, TopMenu } from 'src/app/shared/components';
import { environment } from 'src/environments/environment';// @Injectable({ providedIn: 'root' })
@Injectable()
export class HomeService {constructor(private http: HttpClient) {}getTopMenus() {// return this.topMenus;// return this.http.get(`${environment.baseUrl}/tabs`, //         {params: {iCode: `${environment.iCode}`}}//     );// 添加了拦截器return this.http.get<TopMenu[]>(`${environment.baseUrl}/tabs`);}getChannels() {// return this.channels;// return this.http.get(`${environment.baseUrl}/channels`, //         {params: {iCode: `${environment.iCode}`}}//     );return this.http.get<Channel[]>(`${environment.baseUrl}/channels`);}getImageSliders() {// return this.imageSliders;// return this.http.get(`${environment.baseUrl}/banners`, //         {params: {iCode: `${environment.iCode}`}}//     );return this.http.get<ImageSlider[]>(`${environment.baseUrl}/banners`);}
}

src\app\home\components\home-detail\home-detail.component.ts:

import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ImageSlider } from 'src/app/shared/components';
import { Channel } from 'src/app/shared/components/horizontal-grid';
import { HomeService } from '../../services';@Component({selector: 'app-home-detail',templateUrl: './home-detail.component.html',styleUrls: ['./home-detail.component.scss'],changeDetection: ChangeDetectionStrategy.OnPush  // OnPush策略
})
export class HomeDetailComponent implements OnInit {constructor(private route: ActivatedRoute, private homeService: HomeService,private cd: ChangeDetectorRef) { }selectedTabLink: string | null | undefined;ngOnInit() {this.route.paramMap.subscribe(params => {this.selectedTabLink = params.get('tabLink');this.cd.markForCheck();  // 手动检查});// this.imageSliders = this.homeService.getImageSliders();// this.channels = this.homeService.getChannels();this.homeService.getImageSliders().subscribe(imageSliders => {this.imageSliders = imageSliders;this.cd.markForCheck();});this.homeService.getChannels().subscribe(channels => {this.channels = channels;this.cd.markForCheck();})}imageSliders: ImageSlider[] = [];channels: Channel[] = [];
}

Http拦截器HttpInterceptor

src\app\home\interceptors\param.interceptor.ts:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment';// 拦截器: 处理请求
@Injectable()
export class ParamInterceptor implements HttpInterceptor {intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {const modifiedReq = req.clone({setParams: {icode: environment.iCode}});return next.handle(modifiedReq);}
}

src\app\home\interceptors\notification.interceptor.ts:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';// 拦截器: 处理响应
@Injectable()
export class NotificationInterceptor implements HttpInterceptor {intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {return next.handle(req).pipe(tap((event: HttpEvent<any>) => {if (event instanceof HttpResponse && event.status >= 200 && event.status < 300) {console.log('假装弹出toast, 请求成功.');}}));}
}

src\app\app.module.ts:

import { LOCALE_ID, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeModule, NotificationInterceptor, ParamInterceptor } from './home';
import { SharedModule } from './shared/shared.module';import localZh from '@angular/common/locales/zh-Hans';
import { registerLocaleData } from '@angular/common';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';@NgModule({declarations: [AppComponent],imports: [BrowserModule,AppRoutingModule,SharedModule,AppRoutingModule,HomeModule,HttpClientModule,],providers: [{provide: LOCALE_ID,useValue: 'zh-Hans'},{provide: HTTP_INTERCEPTORS,useClass: ParamInterceptor,multi: true},{provide: HTTP_INTERCEPTORS,useClass: NotificationInterceptor,multi: true}],bootstrap: [AppComponent]
})
export class AppModule {constructor() {// 注册中文相关数据registerLocaleData(localZh, 'zh');}
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部