Snippets Collections
//problem
@Component({
  template: `
    <p>Welcome {{ fullName() }}!</p>
`
})
export class PersonComponent {  
@Input() person: { firstName: string, lastName: string };  constructor() { }  
fullName() {
    return this.person.firstName + ' ' + this.person.lastName
  }  

}

//solusion
@Component({
  template: `
    <p>Welcome {{  name | nameToString  }}!</p>
`
})
export class PersonComponent {
@Input() person: { firstName: string, lastName: string };  constructor() { }  

}


import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'nameToString'
})
export class IdPathPipe implements PipeTransform {
  transform(value): string {
    return value.firstName = value.lastName
request = this.http.get('/users').pipe(
  tap(()=> setContent('Resposta da API'))
)
stopRequest = btnStopRequest$.pipe(
  tap(()=> setContent('Requisicao cancelada'))
)

btnRequest

users$ = this.http.get<User[]>(url).pipe(
	tap(console.log),
  	catchError(this.handleError)
);

private handleError(err: HttpErrorResponse): Observable<never>{
  let errorMessage = `An error occurred: ${err.error.message}`;
  console.error(err);
  return throwError(() => errorMessage);
}
import { fromEvent, delayWhen, interval, of, Subject } from 'rxjs';

const sourceSebjec = new Subject<boolean>();
const sourceAction$ = sourceSebjec.asObservable();

fromEvent(document, 'click').subscribe({
  next: (x) => {
    console.log('CLik next: .. iniciou souce', x);
    sourceSebjec.next(false);
  },
  error: (x) => console.log('Clik erro:', x),
  complete: () => console.log('Clik complete'),
});

sourceAction$.pipe(delayWhen((v) => (v ? interval(2000) : of(0)))).subscribe({
  next: (x) => {
    console.log('Souce next:', x);
  },
  error: (x) => console.log('Souce erro:', x),
  complete: () => console.log('Souce complete'),
});
import { Injectable } from '@angular/core';
import { HttpErrorResponse, HttpClient } from '@angular/common/http';

import { Observable, throwError } from 'rxjs';
import { catchError, shareReplay } from 'rxjs/operators';

import { Product } from './models/product.model';

@Injectable({
  providedIn: 'root'
})
export class ProductsService {
  private const API = 'api/products';

  allProducts$ = this.http.get<Product[]>(this.API).pipe(
    shareReplay(1),
    catchError(this.handleError),
    );

  constructor(private http: HttpClient){}

  private handleError(err: HttpErrorResponse): Observable<never>{
    let errorMessage: string;
    if(err.error instanceof ErrorEvent){
      errorMessage = `Um error ocorreu: ${err.error.message}`;
    }else{
      errorMessage = `Servidor retornou codigo ${err.status}: ${err.message}`;
    }
    console.warn(err);
    return throwError(() => errorMessage)
  }

}
// html
    <ng-container *ngIf="vm$ | async as vm">
      <p *ngIf="vm.user; else userLoading">
      	Welcome back {{ vm.user }}
	  </p>

      <ng-template #userLoading>
        <p>Loading...</p>
        <p *ngIf="vm.userError">There was an error: {{ vm.userError }}</p>
      </ng-template>
    </ng-container>

// component
  user$ = this.userService.userErrored$.pipe(
    startWith(null),
    catchError(() => EMPTY)
  );
  userError$ = this.userService.userErrored$.pipe(
    ignoreElements(),
    startWith(null),
    catchError((err) => of(err))
  );

  vm$ = combineLatest([this.user$,this.userError$]).pipe(
    map(([user, userError]) => ({user, userError}));
  dataSource$ = this.dataSourceAction$.pipe(
    startWith([]),
    switchMap(() => {
      this.isLoadingResultsSubject.next(true);
      return this.getProduct(1).pipe(catchError(() => of(null)))
    }),
    map( data => {
      this.isLoadingResultsSubject.next(false);
      if(data === null) return []
      return data;
    }),);
https://danielk.tech/pt-br/como-ter-uma-nova-tentativa-de-requisicao-http-no-angular-varios-codigos-como-exemplo
const { fromEvent } = rxjs;
const { switchMap, takeUntil, map } = rxjs.operators;

const card = document.querySelector('.card');

const mouseDown$ = fromEvent(card,'mousedown');
const mouseUp$ = fromEvent(document, 'mouseup');
const mouseMove$ = fromEvent(document, 'mousemove');
const dragAndDrop$ = mouseDown$.pipe(
  map(e => ({})),
  switchMap( start => mouseMove$.pipe(
    takeUntil(mouseUp$)
  ))
);
dragAndDrop$.subscribe(v => console.log(v))
    private _categoryId: string;
    
    @Input() set categoryId(value: string) {
    
       this._categoryId = value;
       this.doSomething(this._categoryId);
    
    }
    
    get categoryId(): string {
    
        return this._categoryId;
    
    }
// usage
loadGame(): void {
  this.games = []
  this.loadHandler.start()
  this.http.get<Game[]>.get(this.url).subscribe(
    games => {
      this.loadHandler.finish();
      this.games = games;
    })
}

// service
export class LoadHandler {
  private _isLoading$ = new BehaviorSubject(false);
  isLoading$: Observable<boolean> = this._isLoading$.pipe(
  	switchMap( isLoading => {
      if(!isLoading) {
        return of(false)
      }else{
        return of(true).pipe(delay(1000));
      }
    })
  )

  start(){
    this._isLoading.next(true);
  }
  finish(){
    this._isLoading.next(false);
  }
}
https://fakestoreapi.com/
// component
export class HeroComponent {
 constructor(private activatedRoute: ActivatedRoute) {}
 ngOnInit() {
   this.activatedRoute.data.subscribe(({ hero }) => {
     // do something with your resolved data ...
   })
   // or
   this.hero = this.activatedRoute.data['hero']
 }

}

// resolve
@Injectable({ providedIn: 'root' })
export class HeroResolver implements Resolve<Hero> {
  constructor(private service: HeroService) {}

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<Hero>|Promise<Hero>|Hero {
    return this.service.getHero(route.paramMap.get('id')).pipe(
      catchError(error => of('No data'))
    );
  }
}

// rota
@NgModule({
  imports: [
    RouterModule.forRoot([
      {
        path: 'detail/:id',
        component: HeroDetailComponent,
        resolve: {
          hero: HeroResolver
        }
      }
    ])
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {}
import { combineLatest, Subject, map } from 'rxjs';

var price = 31.99;

/** Declare an Observable
 * Data we can observe
 * over time
 */
const qty$ = new Subject<number>();

/** Emit when the action occurs
 * Hey Observable,
 * here is a new value
 */
const onQuantityChanged = (quantity) => qty$.next(quantity);

/** React to emissions
 * Whenever you
 * change, I`II change
 */
const exPreice$ = qty$.pipe(map((q) => q * price));
const tax$ = exPreice$.pipe(map((t) => Math.round(t * 10.75) / 100));
const deliveryFree$ = exPreice$.pipe(map((q) => (q < 35 ? 5.99 : 0)));
const totalPrice$ = combineLatest([exPreice$, deliveryFree$, tax$]).pipe(
  map(([p, d, t]) => p + d + t)
);
totalPrice$.subscribe(console.log);
onQuantityChanged(2); // 70.86
// component
@ViewChild('inputName', {static: false})
obj: ElementRef;

ngOnInit(){
  this.skipLink()
}

skipLink() {
 this.obj.nativeElement.focus()
}
// html
postWithCategory$ | async

// component
postWithCategory$ = this.postService.postWithCategory$

// post.service.ts
postWithCategory$ = combineLatest([
  this.allPosts$,
  this.categoryService.allCategories$
]).pipe(
  map( ([posts, cat]) => this.mapCategories(posts, cat) )
)

allPosts$ = this.http.get<Post[]>(this.postsUrl).pipe(
  catchError(this.handleError)
);

mapCategories(posts: Post[], cat: PostCatergory[]): Post[]{
  return posts.map( post => ({
    ...post,
    category: cat.find( c => post.categoryId === c.id)?.name
  }) as Post )
}

// category.service
allCategories$ = this.http.get<PostCategory[]>(this.catUrl).pipe(
  catchError(this.handleError),
  shareReplay(1)
);
// html
<div *ngFor"let post of postsForUser$ | async">
 {{ post.title }}
</div>

// component
postsForUser$ = this.entedUser$.pipe(
 switchMap(userName => this.userService.getUserId(userName)),
 switchMap(userId => this.userService.getPostsForUserId(userId))
)

// service
private _userSubject = new Subject<string>();
enteredUser$ = this._userSubject.asObservable();

userChanged(userName: string): void{
  this.enteredUser.next(userName);
}

getUserId(userName: string): Observable<number>{
  return this.http.get<User[]>(`${userUrl}?userName=^${userName}$`).pipe(
   catchError(this.handleError),
   map(users => (users.lenght === 0) ? 0 : users[0].id)
  )
}

getPostsForUserId(userId: number): Observable<Post[]>{
  return this.http.get<Post[]>(`${postsUresgatrl}?userId=^${userId}$`).pipe(
   catchError(this.handleError)
  )
}
user$ = this.http.get<User[]>(url).pipe(
tap(data => console.log(JSON.stringfy(data))),
catchError(this.handleError)
)

privat handleError(err: HttpErrorResponse): Observable<never>{
  let errorMsg = `An error occurred: ${err.error.message}`;
  console.log(err);
  return throwError(()=> errorMsg)
}
//usage
import{MaybeObservable} from '/help/maybe-observable'
import{asObservable} from '/help/as-observable'
getGame$(catId: MaybeObservable<string>){
  return asObservable(catId).pipe(
    switchMap(id => of(this.getGame(id)))
  );
}

// help/as-observable.ts
import{isObservable,of} from 'rxjs'
import{MaybeObservable} from './maybe-observable'
export function asObservable<T>(value: MaybeObservable<T>){
  return isObservable(value) ? value : of(value);
}

// help/maybe-observable.ts
import{Observable} from 'rxjs';
export type MaybeObservable<T> = T | Observable<T>;
catchError( (err, source) => source)
catchError(this.handleError)


  private handleError(err) {
    // 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: string;
    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 = `Backend returned code ${err.status}: ${err.body.error}`;
    }
    console.error(err);
    return throwError(errorMessage);
  }
//html
<div *ngIf="let notice of (news$ | async)"> ...

//compoent
refreshTImer$ = timer(0, 30000)
news$ = this.service.news$
/*ngOnInit*/
this.sub = this.refreshTimer$.subscribe(this.service.refresh$)
/*ngOnDestroy*/
this.sub.unsubscribe()

//service
loadNews$ = this.http.get('/newsfeed')...
refresh$ = new BeharviorSubject(null);
news$ = this.refresh$.pipe(
 exhaustMap( () => this.loadNews$)
)
// app.component.html
<div *ngIf="productSuppliers$ | async as suppliers">
 	<div *ngFor="let supplier of suppliers">
		{{ supplier.name }}
	</div>
</div>
 
 
// app.component.ts
productSuppliers$ = this.productService.productSuppliers$;
 
 
// product.service.ts
selectedProduct$ = ...
productSuppliers$ = this.selectedProduct$.pipe(
  switchMap(product =>
	forkJoin(
		product.supplierIds.map(
			supplierId => this.http.get<Supplier>(`${url}/${supplierId}`))
   )
);
// app.component.html
<div *ngIf="productSupplier$ | async as supplier">
  	{{ supplier.name }}
  </button>
</div>
 
 
// app.component.ts
productSupplier$ = this.productService.productSupplier$;
 
 
// product.service.ts
selectedProduct$ = ...
productSupplier$ = this.selectedProduct$.pipe(
  switchMap(product => this.http.get<Supplier>(`${url}/${product.supplierId}`))
);
star

Thu Feb 09 2023 18:31:09 GMT+0000 (Coordinated Universal Time) https://medium.com/gitconnected/bad-practices-you-should-avoid-with-angular-development-58098e5542d5

#angular #rxjs-pattern
star

Wed Feb 01 2023 15:08:26 GMT+0000 (Coordinated Universal Time) https://youtu.be/VhEfoK5ypg4?t=952

#angular #rxjs-pattern
star

Wed Feb 01 2023 15:00:16 GMT+0000 (Coordinated Universal Time) https://youtu.be/rQTSMbeqv7I?t=1076

#angular #rxjs-pattern
star

Sun Jan 22 2023 02:07:21 GMT+0000 (Coordinated Universal Time)

#angular #rxjs-pattern
star

Sun Jan 22 2023 00:14:43 GMT+0000 (Coordinated Universal Time)

#angular #rxjs-pattern
star

Sat Jan 21 2023 08:03:25 GMT+0000 (Coordinated Universal Time) https://youtu.be/SXOZaWLs4q0?t=740

#angular #rxjs-pattern
star

Fri Jan 20 2023 05:06:51 GMT+0000 (Coordinated Universal Time)

#angular #rxjs-pattern
star

Tue Jan 10 2023 00:17:40 GMT+0000 (Coordinated Universal Time) https://danielk.tech/pt-br/como-ter-uma-nova-tentativa-de-requisicao-http-no-angular-varios-codigos-como-exemplo

#angular #rxjs-pattern
star

Fri Jan 06 2023 21:05:59 GMT+0000 (Coordinated Universal Time)

#angular #rxjs-pattern
star

Tue Jan 03 2023 06:07:16 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/38571812/how-to-detect-when-an-input-value-changes-in-angular

#angular #rxjs-pattern
star

Thu Dec 29 2022 03:15:25 GMT+0000 (Coordinated Universal Time) https://youtu.be/-N6ZrGh2bjc?t=595

#angular #rxjs-pattern
star

Thu Dec 29 2022 02:43:10 GMT+0000 (Coordinated Universal Time)

#angular #rxjs-pattern
star

Thu Dec 29 2022 02:42:35 GMT+0000 (Coordinated Universal Time) https://angular.io/api/router/Resolve

#angular #rxjs-pattern
star

Mon Dec 26 2022 23:12:54 GMT+0000 (Coordinated Universal Time) https://youtu.be/qxjt5vlG58s?t=2309

#angular #rxjs-pattern
star

Mon Dec 26 2022 19:44:12 GMT+0000 (Coordinated Universal Time)

#angular #rxjs-pattern
star

Mon Dec 26 2022 19:37:43 GMT+0000 (Coordinated Universal Time) https://youtu.be/SPy35fOjRyU?t=557

#angular #rxjs-pattern
star

Mon Dec 26 2022 19:15:03 GMT+0000 (Coordinated Universal Time) https://youtu.be/SPy35fOjRyU?t=133

#angular #rxjs-pattern
star

Mon Dec 26 2022 18:00:11 GMT+0000 (Coordinated Universal Time) https://youtu.be/bqIj-m7Uxzk?t=1039

#angular #rxjs-pattern
star

Mon Dec 26 2022 04:26:01 GMT+0000 (Coordinated Universal Time) https://youtu.be/IxOBrYUxetc?t=953

#angular #rxjs-pattern
star

Sat Dec 24 2022 03:27:55 GMT+0000 (Coordinated Universal Time) https://youtu.be/eWU2vlohOwQ?t=734

#angular #rxjs-pattern
star

Fri Dec 23 2022 16:36:37 GMT+0000 (Coordinated Universal Time) https://youtu.be/B-nFj2o03i8?t=821

#angular #rxjs-pattern
star

Wed Dec 21 2022 15:33:13 GMT+0000 (Coordinated Universal Time)

#angular #rxjs-pattern
star

Wed Dec 21 2022 15:26:38 GMT+0000 (Coordinated Universal Time)

#angular #rxjs-pattern

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension