This is my code:
import { Component, OnInit } from '#angular/core';
import { AngularFirestore
, AngularFirestoreCollection
, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
interface Country {
id?: string;
name?: string;
code?: string;
flag?: string;
continent?: string;
}
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Firestore - Documents';
private countryRef: AngularFirestoreCollection<Country>;
docId: any;
constructor( private afs: AngularFirestore ) {
this.countryRef = this.afs.collection('Country', ref => ref.where('code', '==', 'za'));
this.docId = this.countryRef.snapshotChanges().map( changes => {
return changes.map(a => {
const data = a.payload.doc.data() as Country;
data.id = a.payload.doc.id;
return data.id;
});
});
console.log(this.docId);
}
ngOnInit() {}
}
I am expecting an ugly firestore id but instead I am getting this:
Observable {_isScalar: false, source: Observable, operator: MapOperator}
You are getting data as Observable const data = a.payload.doc.data() as Country
you need to subscribe to get the data
this.docId.subscribe(docs => {
docs.forEach(doc => {
console.log(doc.id);
})
})
Here is the recommended way to do it
export class AppComponent implements OnInit {
title = 'Firestore - Documents';
private countryRef: AngularFirestoreCollection<Country>;
docId: Observable<Country[]>;
constructor( private afs: AngularFirestore ) {
this.countryRef = this.afs.collection('Country', ref => ref.where('code', '==', 'za'));
this.docId = this.countryRef.snapshotChanges().map( changes => {
return changes.map(a => {
const data = a.payload.doc.data() as Country;
const id = a.payload.doc.id;
return { id, ...data };
});
});
this.docId.subscribe(docs => {
docs.forEach(doc => {
console.log(doc.id);
})
})
}
ngOnInit() {}
}
Most common practice to retrieve data from firestore using angularfire2 are .valueChanges() and .snapshotChanges(). valueChanges() method provides only the data. It strips all meta data including keys. On other hand .snapshotChanges() will return all data including metadata.
In your code when you do const data = a.payload.doc.data() as Country; it only returns the data with out key. and when you map it to const data id will be ignored because you specified your constructor like id?: string; null safe mode.
Then you get the id const id = a.payload.doc.id; and somehow you need to return it the way you want your interface is. By doing this return { id, ...data }; you are returning all data with id too. and ...data will append all its field one by one after id. you can learn more about this feature here Hope you understand.
Related
Good morning all,
I m currently back in the famous world of web development and I have in mind to develop a tool by using Nest/Prisma/Graphl.
However, I'm struggling a little bit on key element like the following one.
Basically, I can see that, by using the "include" function in Prisma (module.service.ts), I'm getting subModules list: this is the expected behavior.
However, on Graphl side, to cover field resolver (module.resolver.ts), I can see that the same request is executing again to cover SubModules field.....
What am I missing?????
See below the code:
module.module.ts
import { Field, ID, ObjectType } from '#nestjs/graphql'
import { SubModule } from './submodule.model'
#ObjectType()
export class Module {
// eslint-disable-next-line #typescript-eslint/no-unused-vars
#Field((type) => ID)
id: number
name: string
description: string
icon: string
active: boolean
position: number
subModules?: SubModule[]
}
submodule.model.ts
import { Field, ObjectType, ID } from '#nestjs/graphql';
import { Module } from './module.model';
#ObjectType()
export class SubModule {
#Field((type) => ID)
id: number;
name: string;
description: string;
icon: string;
active: boolean;
position: number;
module: Module;
}
module.resolver.ts
import {
Resolver,
Query,
ResolveField,
Parent,
Args,
InputType,
} from '#nestjs/graphql'
import { Module } from 'src/models/module.model'
import { ModuleService } from './module.service'
import { SubModuleService } from './sub-module.service'
#InputType()
class FilterModules {
name?: string
description?: string
icon?: string
active?: boolean
}
// eslint-disable-next-line #typescript-eslint/no-unused-vars
#Resolver((of) => Module)
export class ModuleResolver {
constructor(
private moduleService: ModuleService,
private subModuleService: SubModuleService,
) {}
// eslint-disable-next-line #typescript-eslint/no-unused-vars
#Query((returns) => Module)
async module(#Args('ModuleId') id: number) {
return this.moduleService.module(id)
}
// eslint-disable-next-line #typescript-eslint/no-unused-vars
#Query((returns) => [Module], { nullable: true })
async modules(
#Args({ name: 'skip', defaultValue: 0, nullable: true }) skip: number,
#Args({ name: 'filterModules', defaultValue: '', nullable: true })
filterModules: FilterModules,
) {
return this.moduleService.modules({
skip,
where: {
name: {
contains: filterModules.name,
},
},
})
}
#ResolveField()
async subModules(#Parent() module: Module) {
const { id } = module
return this.subModuleService.subModules({ where: { moduleId: id } })
}
}
module.service.ts
import { Injectable } from '#nestjs/common'
import { PrismaService } from 'src/prisma.service'
import { Prisma, Module } from '#prisma/client'
#Injectable()
export class ModuleService {
constructor(private prisma: PrismaService) {
prisma.$on<any>('query', (event: Prisma.QueryEvent) => {
console.log('Query: ' + event.query)
console.log('Params' + event.params)
console.log('Duration: ' + event.duration + 'ms')
})
}
async module(id: number): Promise<Module | null> {
return this.prisma.module.findUnique({
where: {
id: id || undefined,
},
})
}
async modules(params: {
skip?: number
take?: number
cursor?: Prisma.ModuleWhereUniqueInput
where?: Prisma.ModuleWhereInput
orderBy?: Prisma.ModuleOrderByWithRelationInput
}): Promise<Module[]> {
const { skip, take, cursor, where, orderBy } = params
return this.prisma.module.findMany({
skip,
take,
cursor,
where,
orderBy,
})
}
async updateModule(params: {
where: Prisma.ModuleWhereUniqueInput
data: Prisma.ModuleUpdateInput
}): Promise<Module> {
const { where, data } = params
return this.prisma.module.update({
data,
where,
})
}
}
Thanks in advance for your help
I am using navigateTo to open a page with listview and would like to pass the results back using navigateBack but unable to achieve that. Any idea?
With Service class and Observable, you can achieve this.
notify.service.ts
import { Injectable } from '#angular/core';
import { Subject } from 'rxjs-compat/Subject';
#Injectable({
providedIn: 'root'
})
export class NotifyService {
private refreshDataForView = new Subject<any>();
refreshDataForParentViewObservable$ = this.refreshDataForView.asObservable();
public relaodDataForParentView(data: any) {
if (data) {
this.refreshDataForView.next(data);
}
}
}
Second componenet.ts
constructor(
private notifyService: NotifyService
) { }
goBack() {
this.notifyService.relaodDataForParentView({ data: 'any data you wanrt to pass here ' });
this.router.back();
}
First component.ts
reloadDataSubscription: any;
constructor(
private notifyService: NotifyService
) {}
ngOnInit() {
this.reloadDataSubscription = this.notifyService.refreshDataForParentViewObservable$
.subscribe((res) => {
console.log('======', res);
// do what you want to do with the data passed from second view
});
}
I want to use ngx-translate for items in ng2-select. The only way I can think of is using the translate service and mutate the items' text in ts file prior to binding.
Is there a way to use pipe or directive as I want to make it consistent.
Thanks in advance.
My solution was to create a pipe and use it on the items of the select:
<ng-select [items]="listOfTimeOfExecution | selectOptionsTranslate" ...
and pipe code:
import { Pipe, PipeTransform } from '#angular/core';
import { TranslateService } from 'ng2-translate/ng2-translate';
import { SelectOption } from 'app/shared/entities';
#Pipe({name: 'selectOptionsTranslate'})
export class SelectOptionsTranslatePipe implements PipeTransform {
constructor(public translateService: TranslateService){}
transform(items: Array<SelectOption>) : Array<SelectOption> {
for(let item of items) {
item.text = this.translateService.instant(item.text);
}
return items;
}
}
My solution is inspired by Iosif's for which I can't make it work properly becuz of the async characteristics of the translateService 😣
Secondly, I also need to translate the options when user changes language.
So here's my solution (I wrote a pipe as well) for handling the above 2 issues:
Dependencies:
Angular 6
"#ng-select/ng-select": "2.5.1",
"#ngx-translate/core": "^10.0.2",
translate-options.pipe.ts (Rmbr to import it to the declaration array of app.module.ts)
// ... Rmbr to import the libs ...
#Pipe({
name: 'translateOptions',
})
export class TranslateOptionsPipe implements PipeTransform, OnDestroy {
constructor(private translateService: TranslateService) { }
transform(items: any) {
const observable = Observable.create(observer => {
this.translateService.get(items).subscribe(result => {
// result will be an object
// e.g. { 'JOBS.UX': 'UX Designer', 'JOBS.DEVELOPER': 'Developer' }
observer.next(result);
});
this.translateService.onLangChange.subscribe(event => {
this.translateService.get(items).subscribe(result => {
observer.next(result);
});
})
});
return observable;
}
ngOnDestroy() {
this.translateService.onLangChange.unsubscribe();
}
}
app.component.html
items in the code below will be an array of your translation keys, something like:
['JOBS.DEVELOPER', 'JOBS.UX', 'JOBS.PM']
<ng-select
[addTag]="true"
[addTagText]="to.addTagText || 'Create item: '"
[multiple]="to.multiple"
[closeOnSelect]="!to.multiple"
(change)="onAutoCompleteChange($event)"
>
<ng-option
*ngFor="let item of items | translateOptions | async | keyvalue"
[value]="item.key"
>
{{ item.value }}
</ng-option>
</ng-select>
Hope that helps 💪🏻
The parent that use dropdown will pass an object typed as following to the dropdown component.
export interface IDropdownOptions {
items: any[];
itemType: 'action' | 'divider';
itemLabel: (item: any) => string;
itemClicked?: (item: any) => void; // overwriting default onChange function
itemVisible?: (item: any) => boolean;
itemSelectable?: (item: any) => boolean;
selectedText: (() => string) | string;
shortSelectedText?: (() => string) | string;
// can define more for styling and custom purposes...
}
Then I have my dropdown component to implements ControlValueAccessor to be available in angular form
import { Component, forwardRef, Input, } from '#angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '#angular/forms';
import { get } from 'lodash';
#Component({
selector: 'c-dropdown',
templateUrl: './dropdown.component.html',
providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => DropdownComponent), multi: true }]
})
export class DropdownComponent implements ControlValueAccessor {
#Input() options: IDropdownOptions;
onChange: any = () => {};
get itemLabel(): (item: any) => string {
return !!get(this.options, 'itemLabel')
? this.options.itemLabel
: () => '';
}
get itemClicked(): (item: any) => void {
!!get(this.options, 'itemClicked')
? this.options.itemClicked
: this.onChange;
}
// Getter functions for itemSelectable, itemVisible, etc.
constructor() {}
// Other inherited functions...
registerOnChange(fn: any): void {
this.onChange = fn;
}
}
Inside template's for loop, you can use translate pipe with itemLabel(item).
I need to use the value of another subscription into a subscription. Here is the code. Product value is undefined, what is the best method to access the value?
Code:
#Component({
selector: 'product-page',
templateUrl: 'product-page.html'
})
export class ProductPage {
private product: Product;
this.store.select('products').subscribe(({
product
}) => {
if (product) {
this.product = product;
}
});
this.store.select('plc').subscribe((value: any) = > {
console.log(this.product); // undefined
})
}
You can combine to two selections using the combineLatest operator:
import 'rxjs/add/operator/combineLatest';
// ...
this.store
.select('products')
.combineLatest(this.store.select('plc'))
.subscribe(([products, plc]) => {
// ...
});
I have an Angular 2 component I am trying to put under test, but I am having trouble because the data is set in the ngOnInit function, so is not immediately available in the unit test.
user-view.component.ts:
import {Component, OnInit} from 'angular2/core';
import {RouteParams} from 'angular2/router';
import {User} from './user';
import {UserService} from './user.service';
#Component({
selector: 'user-view',
templateUrl: './components/users/view.html'
})
export class UserViewComponent implements OnInit {
public user: User;
constructor(
private _routeParams: RouteParams,
private _userService: UserService
) {}
ngOnInit() {
const id: number = parseInt(this._routeParams.get('id'));
this._userService
.getUser(id)
.then(user => {
console.info(user);
this.user = user;
});
}
}
user.service.ts:
import {Injectable} from 'angular2/core';
// mock-users is a static JS array
import {users} from './mock-users';
import {User} from './user';
#Injectable()
export class UserService {
getUsers() : Promise<User[]> {
return Promise.resolve(users);
}
getUser(id: number) : Promise<User> {
return Promise.resolve(users[id]);
}
}
user-view.component.spec.ts:
import {
beforeEachProviders,
describe,
expect,
it,
injectAsync,
TestComponentBuilder
} from 'angular2/testing';
import {provide} from 'angular2/core';
import {RouteParams} from 'angular2/router';
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
import {UserViewComponent} from './user-view.component';
import {UserService} from './user.service';
export function main() {
describe('User view component', () => {
beforeEachProviders(() => [
provide(RouteParams, { useValue: new RouteParams({ id: '0' }) }),
UserService
]);
it('should have a name', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
return tcb.createAsync(UserViewComponent)
.then((rootTC) => {
spyOn(console, 'info');
let uvDOMEl = rootTC.nativeElement;
rootTC.detectChanges();
expect(console.info).toHaveBeenCalledWith(0);
expect(DOM.querySelectorAll(uvDOMEl, 'h2').length).toBe(0);
});
}));
});
}
The route param is getting passed correctly, but the view hasn't changed before the tests are run. How do I set up a test that happens after the promise in ngOnInit is resolved?
IMO the best solution for this use case is to just make a synchronous mock service . You can't use fakeAsync for this particular case because of the XHR call for templateUrl. And personally I don't think the "hack" to make ngOnInit return a promise is very elegant. And you should not have to call ngOnInit directly, as it should be called by the framework.
You should already be using mocks anyway, as you are only unit testing the component, and don't want to be dependent on the real service working correctly.
To make a service that is synchronous, simple return the service itself from whatever methods are being called. You can then add your then and catch (subscribe if you are using Observable) methods to the mock, so it acts like a Promise. For example
class MockService {
data;
error;
getData() {
return this;
}
then(callback) {
if (!this.error) {
callback(this.data);
}
return this;
}
catch(callback) {
if (this.error) {
callback(this.error);
}
}
setData(data) {
this.data = data;
}
setError(error) {
this.error = error;
}
}
This has a few benefits. For one it gives you a lot of control over the service during execution, so you can easily customize it's behavior. And of course it's all synchronous.
Here's another example.
A common thing you will see with components is the use of ActivatedRoute and subscribing to its params. This is asynchronous, and done inside the ngOnInit. What I tend to do with this is create a mock for both the ActivatedRoute and the params property. The params property will be a mock object and have some functionality that appears to the outside world like an observable.
export class MockParams {
subscription: Subscription;
error;
constructor(private _parameters?: {[key: string]: any}) {
this.subscription = new Subscription();
spyOn(this.subscription, 'unsubscribe');
}
get params(): MockParams {
return this;
}
subscribe(next: Function, error: Function): Subscription {
if (this._parameters && !this.error) {
next(this._parameters);
}
if (this.error) {
error(this.error);
}
return this.subscription;
}
}
export class MockActivatedRoute {
constructor(public params: MockParams) {}
}
You can see we have a subscribe method that behaves like an Observable#subscribe. Another thing we do is spy on the Subscription so that we can test that it is destroyed. In most cases you will have unsubscribed inside your ngOnDestroy. To set up these mocks in your test you can just do something like
let mockParams: MockParams;
beforeEach(() => {
mockParams = new MockParams({ id: 'one' });
TestBed.configureTestingModule({
imports: [ CommonModule ],
declarations: [ TestComponent ],
providers: [
{ provide: ActivatedRoute, useValue: new MockActivatedRoute(mockParams) }
]
});
});
Now all the params are set for the route, and we have access to the mock params so we can set the error, and also check the subscription spy to make sure its been unsubscribed from.
If you look at the tests below, you will see that they are all synchronous tests. No need for async or fakeAsync, and it passes with flying colors.
Here is the complete test (using RC6)
import { Component, OnInit, OnDestroy, DebugElement } from '#angular/core';
import { CommonModule } from '#angular/common';
import { ActivatedRoute } from '#angular/router';
import { Subscription } from 'rxjs/Subscription';
import { TestBed, async } from '#angular/core/testing';
import { By } from '#angular/platform-browser';
#Component({
template: `
<span *ngIf="id">{{ id }}</span>
<span *ngIf="error">{{ error }}</span>
`
})
export class TestComponent implements OnInit, OnDestroy {
id: string;
error: string;
subscription: Subscription;
constructor(private _route: ActivatedRoute) {}
ngOnInit() {
this.subscription = this._route.params.subscribe(
(params) => {
this.id = params['id'];
},
(error) => {
this.error = error;
}
);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
export class MockParams {
subscription: Subscription;
error;
constructor(private _parameters?: {[key: string]: any}) {
this.subscription = new Subscription();
spyOn(this.subscription, 'unsubscribe');
}
get params(): MockParams {
return this;
}
subscribe(next: Function, error: Function): Subscription {
if (this._parameters && !this.error) {
next(this._parameters);
}
if (this.error) {
error(this.error);
}
return this.subscription;
}
}
export class MockActivatedRoute {
constructor(public params: MockParams) {}
}
describe('component: TestComponent', () => {
let mockParams: MockParams;
beforeEach(() => {
mockParams = new MockParams({ id: 'one' });
TestBed.configureTestingModule({
imports: [ CommonModule ],
declarations: [ TestComponent ],
providers: [
{ provide: ActivatedRoute, useValue: new MockActivatedRoute(mockParams) }
]
});
});
it('should set the id on success', () => {
let fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
let debugEl = fixture.debugElement;
let spanEls: DebugElement[] = debugEl.queryAll(By.css('span'));
expect(spanEls.length).toBe(1);
expect(spanEls[0].nativeElement.innerHTML).toBe('one');
});
it('should set the error on failure', () => {
mockParams.error = 'Something went wrong';
let fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
let debugEl = fixture.debugElement;
let spanEls: DebugElement[] = debugEl.queryAll(By.css('span'));
expect(spanEls.length).toBe(1);
expect(spanEls[0].nativeElement.innerHTML).toBe('Something went wrong');
});
it('should unsubscribe when component is destroyed', () => {
let fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
fixture.destroy();
expect(mockParams.subscription.unsubscribe).toHaveBeenCalled();
});
});
Return a Promise from #ngOnInit:
ngOnInit(): Promise<any> {
const id: number = parseInt(this._routeParams.get('id'));
return this._userService
.getUser(id)
.then(user => {
console.info(user);
this.user = user;
});
}
I ran into the same issue a few days back, and found this to be the most workable solution. As far as I can tell, it doesn't impact anywhere else in the application; since #ngOnInit has no specified return type in the source's TypeScript, I doubt anything in the source code is expecting a return value from that.
Link to OnInit: https://github.com/angular/angular/blob/2.0.0-beta.6/modules/angular2/src/core/linker/interfaces.ts#L79-L122
Edit
In your test, you'd return a new Promise:
it('should have a name', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
// Create a new Promise to allow greater control over when the test finishes
//
return new Promise((resolve, reject) => {
tcb.createAsync(UserViewComponent)
.then((rootTC) => {
// Call ngOnInit manually and put your test inside the callback
//
rootTC.debugElement.componentInstance.ngOnInit().then(() => {
spyOn(console, 'info');
let uvDOMEl = rootTC.nativeElement;
rootTC.detectChanges();
expect(console.info).toHaveBeenCalledWith(0);
expect(DOM.querySelectorAll(uvDOMEl, 'h2').length).toBe(0);
// Test is done
//
resolve();
});
});
}));
}
I had the same issue, here is how I managed to fix it. I had to use fakeAsync and tick.
fakeAsync(
inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
tcb
.overrideProviders(UsersComponent, [
{ provide: UserService, useClass: MockUserService }
])
.createAsync(UsersComponent)
.then(fixture => {
fixture.autoDetectChanges(true);
let component = <UsersComponent>fixture.componentInstance;
component.ngOnInit();
flushMicrotasks();
let element = <HTMLElement>fixture.nativeElement;
let items = element.querySelectorAll('li');
console.log(items);
});
})
)