angular - error TS2339: La propiedad 'takeUntil' no existe en el tipo 'Observable<Foo>' y otros errores de rxjs v.6
Recientemente actualicé MUCHOS paquetes en mi proyecto de Angular.
Antiguo package.json:
{
"name": "data-jitsu",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "^5.2.10",
"@angular/cdk": "^5.2.5",
"@angular/common": "5.2.7",
"@angular/compiler": "5.2.7",
"@angular/core": "5.2.7",
"@angular/forms": "5.2.7",
"@angular/http": "5.2.7",
"@angular/material": "^5.2.5",
"@angular/platform-browser": "5.2.7",
"@angular/platform-browser-dynamic": "5.2.7",
"@angular/router": "5.2.7",
"@types/youtube": "0.0.29",
"angular-froala-wysiwyg": "^2.7.2-1",
"angular2-materialize": "^15.1.10",
"angularfire2": "^4.0.0-rc0",
"core-js": "^2.4.1",
"d3": "^4.13.0",
"firebase": "^3.9.0",
"hammerjs": "^2.0.8",
"jquery": "^3.0.0",
"materialize-css": "^0.100.2",
"ngx-youtube-player": "0.0.41",
"rxjs": "^5.5.6",
"zone.js": "^0.8.4"
},
"devDependencies": {
"@angular/cli": "1.7.2",
"@angular/compiler-cli": "5.2.7",
"@types/bootstrap": "^3.3.36",
"@types/d3": "^4.13.0",
"@types/jasmine": "2.5.38",
"@types/node": "~6.0.60",
"codelyzer": "~2.0.0",
"jasmine-core": "~2.5.2",
"jasmine-spec-reporter": "~3.2.0",
"karma": "~1.4.1",
"karma-chrome-launcher": "~2.0.0",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^0.2.0",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.1.0",
"ts-node": "~2.0.0",
"tslint": "~4.5.0",
"typescript": "2.6.2"
}
}
Nuevo package.json:
{
"name": "data-jitsu",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "^6.0.3",
"@angular/cdk": "^6.3.1",
"@angular/common": "^6.0.3",
"@angular/compiler": "^6.0.3",
"@angular/core": "^6.0.3",
"@angular/forms": "^6.0.3",
"@angular/http": "^6.0.3",
"@angular/material": "^6.2.0",
"@angular/platform-browser": "^6.0.3",
"@angular/platform-browser-dynamic": "^6.0.3",
"@angular/router": "^6.0.3",
"@types/youtube": "^0.0.29",
"angular-froala-wysiwyg": "^2.7.2-1",
"angular2-materialize": "^15.1.10",
"angularfire2": "^5.0.0-rc.11",
"core-js": "^2.4.1",
"d3": "^4.13.0",
"firebase": "^5.0.3",
"hammerjs": "^2.0.8",
"jquery": "^3.0.0",
"materialize-css": "^0.100.2",
"ngx-youtube-player": "0.0.41",
"rxjs": "^6.2.1",
"zone.js": "^0.8.26"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.6.8",
"@angular/cli": "~6.0.8",
"@angular/compiler-cli": "^6.0.3",
"@angular/language-service": "^6.0.3",
"@types/bootstrap": "^3.3.36",
"@types/d3": "^4.13.0",
"@types/jasmine": "~2.8.6",
"@types/jasminewd2": "~2.0.3",
"@types/node": "^10.5.1",
"codelyzer": "~4.2.1",
"jasmine-core": "~2.99.1",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~1.7.1",
"karma-chrome-launcher": "~2.2.0",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "~2.0.0",
"karma-jasmine": "~1.1.1",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.3.0",
"ts-node": "~5.0.1",
"tslint": "~5.9.1",
"typescript": "~2.7.2"
}
}
Cuando ejecuto npm install usando las nuevas actualizaciones de package.json y luego ng serve, obtengo muchos errores de compilación:
ERROR in src/app/all-matches/all-matches.component.ts(35,39): error
TS2339: Property 'takeUntil' does not exist on type
'Observable'. src/app/app.component.ts(28,39): error TS2339:
Property 'takeUntil' does not exist on type 'Observable'.
src/app/authorization.service.ts(19,41): error TS2339: Property 'of'
does not exist on type 'typeof Observable'.
src/app/authorization.service.ts(29,37): error TS2339: Property 'of'
does not exist on type 'typeof Observable'.
src/app/authorization.service.ts(42,39): error TS2339: Property 'of'
does not exist on type 'typeof Observable'.
src/app/authorization.service.ts(66,39): error TS2339: Property 'of'
does not exist on type 'typeof Observable'.
src/app/authorization.service.ts(74,37): error TS2339: Property 'of'
does not exist on type 'typeof Observable'.
src/app/authorization.service.ts(82,39): error TS2339: Property 'of'
does not exist on type 'typeof Observable'.
src/app/database.service.ts(7,31): error TS2305: Module
'"/Users/mf/Desktop/dataJitsu/node_modules/angularfire2/database/index"'
has no exported member 'FirebaseListObservable'.
src/app/database.service.ts(7,55): error TS2305: Module
'"/Users/mf/Desktop/dataJitsu/node_modules/angularfire2/database/index"'
has no exported member 'FirebaseObjectObservable'.
src/app/match-display/match-display.component.ts(27,49): error TS2339:
Property 'takeUntil' does not exist on type 'AngularFireObject<{}>'.
src/app/new-match/new-match.component.ts(10,30): error TS2305: Module
'"/Users/mf/Desktop/dataJitsu/node_modules/angularfire2/database/index"'
has no exported member 'FirebaseListObservable'.
src/app/new-match/new-match.component.ts(10,54): error TS2305: Module
'"/Users/mf/Desktop/dataJitsu/node_modules/angularfire2/database/index"'
has no exported member 'FirebaseObjectObservable'.
src/app/new-match/new-match.component.ts(130,37): error TS2339:
Property 'switchMap' does not exist on type 'Observable'.
src/app/protection.guard.ts(14,34): error TS2339: Property 'map' does
not exist on type 'Observable'.
src/app/test-db/test-db.component.ts(7,30): error TS2305: Module
'"/Users/mf/Desktop/dataJitsu/node_modules/angularfire2/database/index"'
has no exported member 'FirebaseListObservable'.
src/app/test-db/test-db.component.ts(7,54): error TS2305: Module
'"/Users/mf/Desktop/dataJitsu/node_modules/angularfire2/database/index"'
has no exported member 'FirebaseObjectObservable'.
src/app/user-status-report/user-status-report.component.ts(28,39):
error TS2339: Property 'takeUntil' does not exist on type
'Observable'.
src/app/user-status-report/user-status-report.component.ts(33,45):
error TS2339: Property 'subscribe' does not exist on type
'AngularFireObject<{}>'.
src/app/user-status-report/user-status-report.component.ts(35,56):
error TS2339: Property 'takeUntil' does not exist on type
'AngularFireObject<{}>'.
src/app/user-status-report/user-status-report.component.ts(43,66):
error TS2339: Property 'takeUntil' does not exist on type
'AngularFireObject<{}>'.La mayoría de estos errores parecían tener que ver con rxjs, y creo que con razón porque estoy usando rxjs v.6 en la actualización, y mi comprensión es que muchas cosas se rompieron entre v.5 y v.6.
Jugué con la instalación de rxjs-compat npm install rxjs@6 rxjs-compat@6 --save, y puedo confirmar que este paquete, además de ser una adición pesada, no resuelve ninguno de los errores que estoy viendo.
También automatizé algunas de las actualizaciones ejecutando ts-lint, según el consejo aquí y aquí:
npm i -g rxjs-tslint
rxjs-5-to-6-migrate -p [path/to/tsconfig.json]
Recibo el siguiente mensaje:
No se han especificado reglas válidas para los archivos de JavaScript
Supongo que esto significa que no usé las convenciones adecuadas de TypeScript al usar RxJS?
Todavía soy bastante incompetente cuando se trata de rxjs, así que no me queda claro exactamente qué más necesita ser refactorizado.
Pero creo que mi problema en realidad ocurre antes de que aparezca la caja de Pandora de la refactorización:
Eché un vistazo al primer error (el
error TS2339: La propiedad 'takeUntil' no existe en el tipo 'Observable'
uno). El error provino de un método en mi servicio de autenticación. En las declaraciones de importación en la parte superior de este servicio (y en la mayoría de los otros archivos .ts, para el caso), mi IDE resalta muchos errores de "no se puede encontrar el módulo foo" (por ejemplo, "no se puede encontrar el módulo 'rxjs'" para la declaración de importación, import { Observable } from 'rxjs';).
Errores similares en el mismo archivo:
import { Injectable, EventEmitter } from '@angular/core'; ("No se puede encontrar el módulo, '@angular/core'")
importar * como firebase desde 'firebase/app'; ("No se puede encontrar el módulo, 'firebase/app'")
import { Router } from '@angular/router'; ("No se puede encontrar el módulo, '@angular/router'")
Aquí está mi archivo app.module.ts, por si eso es útil:
import { MaterializeModule } from 'angular2-materialize'
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { masterFirebaseConfig } from './api-keys';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AppComponent } from './app.component';
import { YoutubeComponent } from './youtube/youtube.component';
import { routing } from './app.routing';
import { NewMatchComponent } from './new-match/new-match.component';
import { CreateAccountComponent } from './create-account/create-account.component';
import { TestDbComponent } from './test-db/test-db.component';
import { LandingComponent } from './landing/landing.component';
import { MatchDisplayComponent } from './match-display/match-display.component';
import { AuthorizationService } from './authorization.service';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { DatabaseService } from './database.service';
import { TextTransformationService } from './text-transformation.service';
import { ValidationService } from './validation.service';
import { LoginComponent } from './login/login.component';
import { ProtectionGuard } from './protection.guard';
import { AllMatchesComponent } from './all-matches/all-matches.component';
import { AnnotationDisplayComponent } from './annotation-display/annotation-display.component';
import { D3Service } from './d3.service';
import { NotfoundComponent } from './notfound/notfound.component';
import { UserStatusReportComponent } from './user-status-report/user-status-report.component';
import { PaymentOrAnnotationDetailsComponent } from './payment-or-annotation-details/payment-or-annotation-details.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatSelectModule } from '@angular/material/select';
import { MatOptionModule } from '@angular/material/core';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material';
import { MatTableModule } from '@angular/material/table';
// import { MatTreeModule } from '@angular/material';
import { MatTreeModule } from '@angular/material/tree';
import { MatSortModule } from '@angular/material';
import { MatDatepickerModule, MatNativeDateModule, MatPaginatorModule } from '@angular/material';
import {MatProgressSpinnerModule} from '@angular/material/progress-spinner';
import { CdkTreeModule } from '@angular/cdk/tree';
export const firebaseConfig = {
apiKey: masterFirebaseConfig.apiKey,
authDomain: masterFirebaseConfig.authDomain,
databaseURL: masterFirebaseConfig.databaseURL,
storageBucket: masterFirebaseConfig.storageBucket
};
@NgModule({
declarations: [
AppComponent,
YoutubeComponent,
NewMatchComponent,
CreateAccountComponent,
TestDbComponent,
LandingComponent,
MatchDisplayComponent,
LoginComponent,
AllMatchesComponent,
AnnotationDisplayComponent,
NotfoundComponent,
UserStatusReportComponent,
PaymentOrAnnotationDetailsComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
routing,
MaterializeModule,
ReactiveFormsModule,
AngularFireModule.initializeApp(firebaseConfig),
AngularFireDatabaseModule,
AngularFireAuthModule,
BrowserAnimationsModule,
MatSlideToggleModule,
CdkTreeModule,
MatSelectModule,
MatOptionModule,
MatInputModule,
MatNativeDateModule,
MatDatepickerModule,
MatTableModule,
MatSelectModule,
MatSortModule,
MatProgressSpinnerModule,
MatPaginatorModule,
MatTreeModule
],
providers: [AuthorizationService, DatabaseService, ProtectionGuard, D3Service, ValidationService, TextTransformationService],
bootstrap: [AppComponent]
})
export class AppModule { }
Y aquí está la rama del repositorio que contiene todos estos problemas.
git clone https://github.com/Atticus29/dataJitsu.git
cd dataJitsu
git checkout version-hell-SO
npm install
ng serve
¡Cualquier consejo de solución de problemas o soluciones inmediatas a los problemas de importación son bienvenidos y alentados!
Respuesta #1
Parece que tus operadores todavía están encadenados al estilo de rxjs 5.x.
Entonces, para recapitular lo que cambió en rxjs6:
Las importaciones son diferentes. Ahora, debes importar Observable, Subject, BehaviorSubject, etc., y los métodos que estaban en 'rxjs/add/observable' de manera diferente. Así que todos estos deben importarse desde 'rxjs'. Por ejemplo:
import {Observable, Subject, of, from} from 'rxjs';Alternativamente, todos los operadores como map, concat, do (que ahora se llama tap), etc., deben importarse desde
rxjs/operators. así que algo como:import { map, tap, takeUntil} from 'rxjs/operators';Creo que tus importaciones son bastante sensatas.
Debes usar pipes en lugar de encadenar tus operadores. Por ejemplo, en tu archivo all-matches.components.ts, línea 33, si reemplazas:
this.authService.getCurrentUser().takeUntil(this.ngUnsubscribe).subscribe(user=>{por
this.authService.getCurrentUser().pipe(takeUntil(this.ngUnsubscribe)).subscribe(user=>{tu error de takeUntil desaparecerá.
De la misma manera, en lugar de
Observable.of(true), deberías importar el operador of y usarof(true).Puedes probar esto en tu archivo authorization.service.ts. Todos los "de errores" serán solucionados.
tal vez deberías inspeccionar esto
Con respecto a los errores de importación relacionados con archivos personalizados, por favor verifique que los archivos realmente existen. Por ejemplo:
ERROR in src/app/app.module.ts(6,38): error TS2307: Cannot find module './api-keys'relacionado con
import { masterFirebaseConfig } from './api-keys'es normal, ya que este archivo './api-keys' no existe. PD: tal vez no tengas estos errores si las claves no están almacenadas en git, si es así ignóralo.
Finalmente, sobre AngularFire5.0, deberías usar uno de los operadores:
Db.list('items').subscribe(console.log)se convierte (con el método valueChanges) :
Db.list<Item>('items').valueChanges().subscribe(console.log)Más información: https://github.com/angular/angularfire2/blob/master/docs/version-5-upgrade.md
¡Buena suerte!