Connects a collection viewer firebase - javascript

I want to create a table with table material i was watching a tutorial about connecting material table to firebase but i got a error that i didn't understand
The error message upon connect:
Property 'connect' in type 'chauffeurDataSource' is not assignable to the same property in base type 'DataSource<any>'.
Type '() => void' is not assignable to type '(collectionViewer: CollectionViewer) => Observable<any[] | readonly any[]>'.
Type 'void' is not assignable to type 'Observable<any[] | readonly any[]>'.
This is my code, in landing.componnet.ts:
import { Component, OnInit } from "#angular/core";
import { CollectionViewer, DataSource } from '#angular/cdk/collections'
import {AngularFirestore} from "#angular/fire/firestore";
import {chauffeurs} from '../../shared/models/chauffeur'
import { chauffeurService } from "src/app/shared/service/ChaufffeurService";
import { Observable } from "rxjs-compat";
#Component({
selector: "app-landing",
templateUrl: "./landing.component.html",
})
export class LandingComponent implements OnInit {
displayedColumns = ['nometprenom', 'Active', 'Nombre de lot', 'Montant total du lot', 'Nombre de colies livrée','Sommes livrées','Sommes livrée','Somme dues'];
dataSource =new chauffeurDataSource(this.chauffeur.getchauffeur())
constructor(private chauffeur:chauffeurService) {}
ngOnInit(): void {}
}
export class chauffeurDataSource extends DataSource<any> {
connect() {
return this.chauffeur.getchauffeur();
}
disconnect(collectionViewer: CollectionViewer): void {
throw new Error("Method not implemented.");
}
constructor(private chauffeur: chauffeurService){
super()
}
}

Related

error TS2740 Type 'DeepPartial<Quiz>[]' is missing the following properties from type 'Question': id, question, hasId, save, and 4 more

I don't know how to fix this error. Does anyone know what I need to fix to get this code to work?
import { Injectable } from '#nestjs/common';
import { InjectRepository } from '#nestjs/typeorm';
import { CreateQuestionDto } from './dto/create-question.dto';
import { Question } from './question.entity';
import { QuestionRepository } from './question.repository';
#Injectable()
export class QuestionService {
constructor(
#InjectRepository(QuestionRepository)
private questionRepository: QuestionRepository,
) {}
async createQuestion(question: CreateQuestionDto): Promise<Question> {
return await this.questionRepository.save(question);
}
}
Returns the following error:
src/modules/quiz/question.service.ts:15:5 - error TS2740: Type 'DeepPartial[]' is missing the following properties from type 'Question': id, question, hasId, save, and 4 more.
15 return await this.questionRepository.save(question);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
src/modules/quiz/question.service.ts:15:47 - error TS2769: No overload matches this call.
Overload 1 of 4, '(entities: DeepPartial[], options?: SaveOptions): Promise<(DeepPartial & Quiz)[]>', gave the following error.
Argument of type 'CreateQuestionDto' is not assignable to parameter of type 'DeepPartial[]'.
Type 'CreateQuestionDto' is missing the following properties from type 'DeepPartial[]': length, pop, push, concat, and 29 more.
Overload 2 of 4, '(entity: DeepPartial, options?: SaveOptions): Promise<DeepPartial & Quiz>', gave the following error.
Type 'CreateQuestionDto' has no properties in common with type 'DeepPartial'.
15 return await this.questionRepository.save(question);
Question entity:
import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
#Entity('questions')
export class Question extends BaseEntity {
#PrimaryGeneratedColumn()
id: string;
#Column({
type: 'varchar',
})
question: string;
}
Question repository:
import { EntityRepository, Repository } from 'typeorm';
import { Quiz } from './quiz.entity';
#EntityRepository(Quiz)
export class QuestionRepository extends Repository<Quiz> {}
CreateQuestion dto:
import { IsNotEmpty, Length } from 'class-validator';
export class CreateQuestionDto {
#IsNotEmpty()
#Length(3, 255)
question: string;
}
Question repository:
import { EntityRepository, Repository } from 'typeorm';
import { Quiz } from './quiz.entity';
#EntityRepository(Quiz)
export class QuestionRepository extends Repository<Quiz> {}
The problem is that your QuestionRepository is pointing to another entity (Quiz).
Change it to:
export class QuestionRepository extends Repository<Question> {}
That way you can avoid the any clause and use the dto directly on the save call.
async createQuestion(question: CreateQuestionDto): Promise<Question> {
return await this.questionRepository.save(question);
}

How to push data and detect changes in angular 2 + version?

In previous angular version we had $scope.apply to detect changes , So i below code i have data from detailService that is printed now i am pushing data to object its throwing error object property is undefined , what is correct approach in new angular version to push data to array and bind it to the dom ?
app.component.ts
import { Component, OnInit,Pipe, PipeTransform, EventEmitter, Output } from '#angular/core';
import { DetailService } from '../detail.service';
import { StreamService } from '../stream.service';
import { MatTableDataSource } from '#angular/material';
import {GtConfig} from '#angular-generic-table/core';
import { GenericTableComponent} from '#angular-generic-table/core';
import * as io from 'socket.io-client';
export interface Element {
ticketNum: number;
ticketOpened: number;
eventType: string;
riskIndex: string;
riskValue: number;
severity: string;
lastModifiedDate: number;
assetID: string;
}
#Component({
selector: 'app-detail',
templateUrl: './detail.component.html',
styleUrls: ['./detail.component.css'],
})
export class DetailComponent{
messageArray: any[];
message1:Object = {};
public secondConfigObject: GtConfig<any>;
constructor(private detailService: DetailService) {
this.secondConfigObject = {
settings: this.getBaseSettings(),
fields: this.getBaseFields(),
data: []
};
};
ngOnInit() {
this.detailService.currentMessage1.subscribe(message1 => {
console.log('eventINDetailComp',message1);
this.secondConfigObject.data.push(message1);
});
}
}
app.component.html
<div class="table-responsive">
<generic-table [gtClasses]="'table-hover'" #myCustomTable [gtSettings]="secondConfigObject.settings" [gtFields]="secondConfigObject.fields" [gtData]="secondConfigObject.data"></generic-table>
</div>
You should move the code from the constructor to the start of the ngOnInit() function so the data gets set once the page has been created, not during.
As for data binding, variables on the screen/html will automatically update when they are changed in the code behind

Callback for FirebaseObservable

I have a simple setup with some code that counts the number of items in my FireBase database.
This is working but the button is empty until the data is loaded.
Is there a way to hide the button until this is done? Or set a loading state until this is done?
export class ButtonComponent implements OnInit {
likes: FirebaseListObservable<any[]>;
constructor(private angularFire: AngularFire) {}
ngOnInit() {
this.getLikes();
}
getLikes() {
this.likes = this.angularFire.database.list('/likes');
}
}
This is my button template
<button (click)="onClicked()" class="button">
{{(likes | async)?.length}}
</button>
I tried subscribing() to it
export class ButtonComponent {
likes: FirebaseListObservable<any[]>;
constructor(private angularFire: AngularFire) {
this.angularFire.database.list('/likes').subscribe(
response => {this.likes = response}
);
}
onClicked() {
this.likes.push({'like': new Date().toISOString()})
}
}
But that returns the following error:
Type 'any[]' is not assignable to type 'FirebaseListObservable<any[]>

EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property '0' of null any suggestion please?

I am facing this problem since I started to learn angular2.
news.service
#Injectable()
export class NewsServices {
private news: News[] = [];
constructor(private _http: Http) {}
getSingleNews(id: string): Observable <SingleNews[]> {
return this._http.get(`http://watania.info/getNewsById/${id}`)
.map((response: Response) => response.json());
}
export interface SpecialNews {
id: string;
title: string;
url_title: string;
image: string;
category: string;
summary: string;
date_to_publish: string;
}
news.component.ts
import { ActivatedRoute, Router } from '#angular/router';
import { Component, OnDestroy, OnInit } from '#angular/core';
import { NewsServices, SingleNews } from '../../services/news.services';
import { News } from './../../services/news.services';
import { Subscription } from 'rxjs/Rx';
import { VideosPage } from './../../services/videos.service';
#Component({
selector: 'wn-single-news',
templateUrl: './single-news.component.html',
styleUrls: ['./single-news.component.css']
})
export class SingleNewsComponent implements OnInit, OnDestroy {
sub: Subscription;
private selectednews: SingleNews[]= [];
private relatedNews: News[]= [];
constructor(private _newsService: NewsServices,
private route: ActivatedRoute) {}
ngOnInit (): void {
this.sub = this.route.params.subscribe(params => {
let id = params['id'];
this._newsService.getSingleNews(id).subscribe(
selectednews => this.selectednews = selectednews);
this._newsService.getRelatedNews(id).subscribe(
relatedNews => this.relatedNews = relatedNews);
});
console.log(this.relatedNews[0])
}
ngOnDestroy() {
console.log(this.relatedNews[0])
this.sub.unsubscribe();
}
}
The problem is that when I try to use any service like the above one, in any of my component like news component, I got undefined in the console for console.log(this.relatedNews[0]) in ngOnInit, but for console.log(this.relatedNews[0]) in ngOnDestroy I got the array. Moreover I can use the same variable in my template.
<h1 class="news-header"><span></span> {{selectednews[0]?.title}}</h1>
It worked fine when use the variable in the template as shown above. but whenever I try to use it in the component I got
EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property '0' of null
any suggestion please?
this._newsService.getRelatedNews(id).subscribe(
relatedNews => this.relatedNews = relatedNews);
});
is an async operation. You need to do your operations with relatedNews inside the callback(subscribe) like this:
this._newsService.getRelatedNews(id).subscribe(
(relatedNews) => {
this.relatedNews = relatedNews;
console.log(this.relatedNews[0]);
});
Put your console.log(this.relatedNews[0]) inside the callback of your service like this:
this._newsService.getRelatedNews(id).subscribe(
relatedNews => this.relatedNews = relatedNews);
console.log(this.relatedNews[0])
});
normally your console.log will return your object

Type 'CanDeactivate' is not generic

Following the Angular 2 example here. There is can error right after the implements while running tsc:
error TS2315: Type 'CanDeactivate' is not generic.
import { Injectable } from '#angular/core';
import { CanDeactivate } from '#angular/router';
import { Observable } from 'rxjs/Observable';
export interface CanComponentDeactivate {
canDeactivate: () => boolean | Observable<boolean>;
}
#Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate): Observable<boolean> | boolean {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
This is confusing to me, as the interface has already been declared. Why do I see an error there?

Categories

Resources