首页 > 其他分享 >[Angular v16] Signals

[Angular v16] Signals

时间:2023-04-13 14:13:54浏览次数:48  
标签:errorMessage vehicles v16 private Signals error vehicle import Angular

Service:

fromObservable & fromSignalcan transform observable to and from signals.

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable, signal } from '@angular/core';
import {
  catchError,
  filter,
  forkJoin,
  map,
  Observable,
  shareReplay,
  switchMap,
  throwError
} from 'rxjs';
import { fromObservable, fromSignal } from '@angular/core/rxjs-interop';
import { Film, Vehicle, VehicleResponse } from './vehicle';

@Injectable({
  providedIn: 'root'
})
export class VehicleService {
  private url = 'https://swapi.py4e.com/api/vehicles';

  // First page of vehicles
  // If the price is empty, randomly assign a price
  // (We can't modify the backend in this demo)
  private vehicles$ = this.http.get<VehicleResponse>(this.url).pipe(
    map((data) =>
      data.results.map((v) => ({
        ...v,
        cost_in_credits: isNaN(Number(v.cost_in_credits))
          ? String(Math.random() * 100000)
          : v.cost_in_credits,
      }) as Vehicle)
    ),
    shareReplay(1),
    catchError(this.handleError)
  );

  // Expose signals from this service
  vehicles = fromObservable<Vehicle[], Vehicle[]>(this.vehicles$, []);
  selectedVehicle = signal<Vehicle | undefined>(undefined);
  
  private vehicleFilms$ = fromSignal(this.selectedVehicle).pipe(
    filter(Boolean),
    switchMap(vehicle =>
      forkJoin(vehicle.films.map(link =>
        this.http.get<Film>(link)))
    )
  );
  vehicleFilms = fromObservable<Film[], Film[]>(this.vehicleFilms$, []);

  constructor(private http: HttpClient) {
  }

  vehicleSelected(vehicleName: string) {
    const foundVehicle = this.vehicles().find((v) => v.name === vehicleName);
    this.selectedVehicle.set(foundVehicle);
  }

  private handleError(err: HttpErrorResponse): Observable<never> {
    // in a real world app, we may send the server to some remote logging infrastructure
    // instead of just logging it to the console
    let errorMessage = '';
    if (err.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      errorMessage = `An error occurred: ${err.error.message}`;
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      errorMessage = `Server returned code: ${err.status}, error message is: ${err.message
        }`;
    }
    console.error(errorMessage);
    return throwError(() => errorMessage);
  }
}

 

Component:

Only need to refer the signals in service:

import { Component } from '@angular/core';
import { NgFor, NgClass, NgIf, AsyncPipe } from '@angular/common';
import { VehicleService } from '../vehicle.service';

@Component({
  selector: 'sw-vehicle-list',
  standalone: true,
  imports: [AsyncPipe, NgClass, NgFor, NgIf],
  templateUrl: './vehicle-list.component.html'
})
export class VehicleListComponent {
  pageTitle = 'Vehicles';
  errorMessage = '';

  // Component signals
  vehicles = this.vehicleService.vehicles;
  selectedVehicle = this.vehicleService.selectedVehicle;

  constructor(private vehicleService: VehicleService) { }

  // When a vehicle is selected, emit the selected vehicle name
  onSelected(vehicleName: string): void {
    this.vehicleService.vehicleSelected(vehicleName);
  }

}

 

Template:

<div class="card">
  <div class="card-header">
    {{pageTitle}}
  </div>

  <div class='card-body'
       *ngIf="vehicles().length">

    <div class="list-group">
      <button type="button"
              class="list-group-item"
              *ngFor="let vehicle of vehicles()"
              [ngClass]="{'active': vehicle?.name === selectedVehicle()?.name}"
              (click)="onSelected(vehicle.name)">
        {{ vehicle.name }}
      </button>
    </div>
  </div>

  <div class="alert alert-danger"
       *ngIf="errorMessage">
    {{errorMessage }}
  </div>
</div>

 

标签:errorMessage,vehicles,v16,private,Signals,error,vehicle,import,Angular
From: https://www.cnblogs.com/Answer1215/p/17314568.html

相关文章

  • Angular + quill实现富文本编辑器
    前言由于需要一个富文本编辑器来编辑一些网页内容,手动编辑后存储到数据库比较麻烦,所以着手实现一个自己的富文本编辑器,来编辑和存储一些html文件.这里使用Angular框架,加Quill库实现.ngx-quill:https://github.com/KillerCodeMonkey/ngx-quillquill官网:https://quil......
  • Angular 复习与进阶系列 – Naming Conversion
    前言命名规范对项目维护是很重要的.Angular对项目的渗透很大的,必须做好命名规范,不然会很乱. Angular NamingConversionInjectionToken=UPPER_SNAKE_CAREconstSERVICE_CONFIG_TOKEN=newInjectionToken('ServiceConfig'); elementattributeandproperty......
  • angular项目启动报Another process, with id 24289, is currently running ngcc.
    在npmbuild时突然停下来,再启动就启不起来了。看报错信息是端口被占用,在任务管理器中也找不到这个端口重启vscode、重启电脑都不好使。。可以通过删除node_modules再重新npminstall解决! ......
  • 什么是 Angular library 的 secondary entry points?
    在Angular应用程序和库中,secondaryentrypoints(次要入口点)是指与主入口点不同的导出和发布方式。主入口点是指在package.json文件中声明的默认的入口点,它通常包含了该库的主要功能和API。而secondaryentrypoints则是在Angularlibrary项目中定义的额外的入口点,它们可......
  • 力士乐驱动调试软件13v16版本,中文版本的
    力士乐驱动调试软件13v16版本,中文版本的,用这个调试过项目,配套还有好多手册YID:5189656708457614......
  • 关于 Angular 应用部署时的 base-href 参数
    import{existsSync}from'fs';server.get(['/shop/*','/shop'],(req,res)=>{res.render(indexHtml,{req,providers:[{provide:APP_BASE_HREF,useValue:req.baseUrl}],});});server.set('views',distFo......
  • Angular 应用里 server.ts 文件的 APP_BASE_HREF token 的用法?
    Angular应用里server.ts文件,下面这段代码的含义?server.get('*',(req,res)=>{res.render(indexHtml,{req,providers:[{provide:APP_BASE_HREF,useValue:req.baseUrl}],});});在Angular应用中,server.ts文件是用于构建服务器端渲染(S......
  • 一文搞定:前端如何选择Angular、React和Vue三大主流框架
    在前端开发领域,目前最流行的三个框架是Angular、React和Vue.js。这些框架非常高效,并且它们各自具有一系列的优缺点。在AI辅助编程工具CodeGeeX的后台中,也看到有大量的前端开发者使用这三个框架,并且Vue的使用率在CodeGeeX的后台中,持续走高。接下来我们针对Angular、React和Vue.js......
  • Angular Generating browser application bundles (phase: setup)...An unhandled ex
    PSF:\WorkGitHub\angulard3tree>ngserve⠋Generatingbrowserapplicationbundles(phase:setup)...Anunhandledexceptionoccurred:webpack_1.AngularWebpackPluginisnotaconstructorSee"C:\Users\ghosii\AppData\Local\Temp\ng-daZXzA\angu......
  • Angular Generating browser application bundles (phase: setup)...An unhandled ex
     PSF:\WorkGitHub\angulard3tree>ngserve⠋Generatingbrowserapplicationbundles(phase:setup)...Anunhandledexceptionoccurred:webpack_1.AngularWebpackPluginisnotaconstructorSee"C:\Users\ghosii\AppData\Local\Temp\ng-daZXzA\angu......