将值传递给构造函数时使构造函数工作的问题

Posted

技术标签:

【中文标题】将值传递给构造函数时使构造函数工作的问题【英文标题】:Issue with getting a constructor to work when passing a value into it 【发布时间】:2018-10-31 21:28:57 【问题描述】:

我有这个代码:

import Component, OnInit from '@angular/core';
import FirebaseListObservable, FirebaseObjectObservable, AngularFireDatabase from 'angularfire2/database-deprecated';
import Item from '../shared/item';
import ItemService from '../shared/item.service';

@Component(
  selector: 'app-items-list',
  templateUrl: './items-list.component.html',
  styleUrls: ['./items-list.component.scss']
)
export class ItemsListComponent implements OnInit 

  public items: FirebaseListObservable<any[]>;

  constructor(private itemSvc: ItemService) 
  

  ngOnInit() 
    this.items = this.itemSvc.getItemsList(limitToLast: 10);
  

  deleteItems() 
    this.itemSvc.deleteAll();
  

当我尝试运行它时,我得到了非常有用的ERROR Error: "[object Object]"。我正在评论,直到错误消失。看起来我的构造函数有问题,但我不知道是什么。有什么想法吗?

这是我的 ItemService:

import Injectable from '@angular/core';
import FirebaseListObservable, FirebaseObjectObservable, AngularFireDatabase from 'angularfire2/database-deprecated';
import Item from './item';

@Injectable()
export class ItemService 

  private basePath: string = '/items';

  items: FirebaseListObservable<Item[]> = null; //  list of objects
  item: FirebaseObjectObservable<Item> = null; //   single object

  constructor(private db: AngularFireDatabase) 
  

  getItemsList(query = ): FirebaseListObservable<any[]> 
    this.items = this.db.list(this.basePath, 
      query: query
    );
    return this.items;
  

  // Return a single observable item
  getItem(key: string): FirebaseObjectObservable<Item> 
    const itemPath = `$this.basePath/$key`;
    this.item = this.db.object(itemPath);
    return this.item;
  

  createItem(item: Item): void 
    this.items.push(item)
      // .catch(error => this.handleError(error));
  


  // Update an existing item
  updateItem(key: string, value: any): void 
    this.items.update(key, value)
      .catch(error => this.handleError(error));
  

  // Deletes a single item
  deleteItem(key: string): void 
    this.items.remove(key)
      .catch(error => this.handleError(error));
  

  // Deletes the entire list of items
  deleteAll(): void 
    this.items.remove()
      .catch(error => this.handleError(error));
  

  // Default error handling for all actions
  private handleError(error) 
    console.log(error);
  

HTML 模板:

<div *ngFor="let item of items | async" >
  <app-item-detail [item]='item'></app-item-detail>
</div>
<!--<button (click)='deleteItems()'>Delete Entire List</button>-->

app.module.ts文件:

import BrowserModule from '@angular/platform-browser';
import NgModule from '@angular/core';
import RouterModule from '@angular/router';
import rootRouterConfig from './app.routes';
import AngularFireModule from 'angularfire2';
import AngularFirestoreModule from 'angularfire2/firestore';
import AngularFireAuthModule from 'angularfire2/auth';
import environment from '../environments/environment';
import LoginComponent from './login/login.component';
import UserComponent from './user/user.component';
import RegisterComponent from './register/register.component';
import UserResolver from './user/user.resolver';
import AuthGuard from './core/auth.guard';
import AuthService from './core/auth.service';
import UserService from './core/user.service';
import ReactiveFormsModule from '@angular/forms';

import AppComponent from './app.component';
import HomeComponent from './home/home.component';
import AboutComponent from './about/about.component';
import ItemsListComponent from './items/items-list/items-list.component';
import ItemDetailComponent from './items/item-detail/item-detail.component';
import ItemFormexportComponent from './items/item-formexport/item-formexport.component';
import ItemFormComponent from './items/item-form/item-form.component';

@NgModule(
  declarations: [
    AppComponent,
    LoginComponent,
    UserComponent,
    RegisterComponent,
    HomeComponent,
    AboutComponent,
    ItemsListComponent,
    ItemDetailComponent,
    ItemFormexportComponent,
    ItemFormComponent,
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule,
    RouterModule.forRoot(rootRouterConfig, useHash: false),
    AngularFireModule.initializeApp(environment.firebase),
    AngularFirestoreModule, // imports firebase/firestore, only needed for database features
    AngularFireAuthModule, // imports firebase/auth, only needed for auth features
  ],
  providers: [AuthService, UserService, UserResolver, AuthGuard],
  bootstrap: [AppComponent]
)
export class AppModule 

我是 Angular 的新手,所以如果我遗漏了什么,请告诉我,我会添加它。

【问题讨论】:

如果我这样做,它不会在ngOnInitdeleteItems 中找到,对吧? 您在模板 html 中使用异步管道吗? 是的。我附上代码 你的构造函数完全没问题。 @NikolaLukic - 注入的参数可以是私有的,它们应该是 - 只能在组件范围内使用。 您是否在模块providers 部分中注册了注入的服务? 【参考方案1】:

确保在 app.module.ts 文件中导入 AngularFireDatabaseModule。由于您的服务正在使用 AngularFireDatabase。

请参阅以下链接了解更多信息。 https://github.com/angular/angularfire2/blob/master/docs/storage/storage.md

import  AngularFireModule  from 'angularfire2';
// for AngularFireDatabase
import  AngularFireDatabaseModule  from 'angularfire2/database';
import  AngularFireDatabase, FirebaseObjectObservable  from 'angularfire2/database';
// for AngularFireAuth
import  AngularFireAuthModule  from 'angularfire2/auth';
import  AngularFireAuth  from 'angularfire2/auth';

@NgModule(
  imports: [
    AngularFireModule.initializeApp(         <---- main module
      apiKey: ...,
      authDomain: '...',
      databaseURL: '...',
      storageBucket: '...',
      messagingSenderId: '...'
    ),                                       
    AngularFireDatabaseModule,                <---- for database 
    AngularFireAuthModule                     <---- for auth
  ]
)

【讨论】:

在这里:import AngularFireDatabase, FirebaseObjectObservable from 'angularfire2/database'; 我收到此错误:Module "..." has no exported member "FirebaseObjectObservable"。他们会再次移动它吗? @alex3wielki,不确定 Alex。请参阅此链接。它可能会帮助你。 github.com/angular/angularfire2/issues/1382 好的,我修复了参考错误,但您能解释一下这应该如何提供帮助吗?我只是在导入新模块。

以上是关于将值传递给构造函数时使构造函数工作的问题的主要内容,如果未能解决你的问题,请参考以下文章

如何将向量传递给基于推力的 odeint 观察者的构造函数,以便可以在函子中读取它

构造函数不将初始数组值传递给方法

我如何将参数传递给构造函数? [关闭]

任何 .NET ORM 是不是“正确”使用构造函数?

将数组传递给构造函数会产生大小为 1 的数组? [复制]

通过引用传递给构造函数