我正在尝试对Angular2和Firebase数据库进行获取请求。发布请求可以很好地工作,但是获取请求将不起作用。我不知道这是怎么做的。

这是我的list.component

export class ListComponent implements OnInit {
   notes = []
  constructor(
    private store: Store,
    private noteService: ListingService
  ) {

  }

 ngOnInit() {
   this.noteService.getNotes()
    .subscribe();

    this.store.changes.pluck('notes')
    .subscribe((notes: any) => { this.notes = notes;  console.log(this.notes)});

  }

  onCreateNote(note) {
    this.noteService.createNote(note)
    .subscribe();
  }

  onNoteChecked(note) {
    this.noteService.completeNote(note)
    .subscribe();
  }


}


这是我的api.service

export class ApiService {
  headers: Headers = new Headers({
    'Content-Type': 'application/json',
    Accept: 'application/json'
  });

  api_url: string = 'https://someapp-94b34.firebaseio.com/';
  constructor(private http: Http) {

  }

  private getJson(response: Response) {
    return response.json();
  }

  private checkForError(response: Response): Response {
    if (response.status >= 200 && response.status < 300) {
      return response;
    } else {
      var error = new Error(response.statusText)
      error['response'] = response;
      console.error(error);
      throw error;
    }
  }

  get(path: string): Observable<any> {
    return this.http.get(`${this.api_url}${path}.json`, { headers: this.headers })
    .map(this.checkForError)
    .catch(err => Observable.throw(err))
    .map(this.getJson)
  }

  post(path: string, body): Observable<any> {
    return this.http.post(
      `${this.api_url}${path}.json`,
      JSON.stringify(body),
      { headers: this.headers }
    )
    .map(this.checkForError)
    .catch(err => Observable.throw(err))
    .map(this.getJson)
  }
}


这是我的listing.service

export class ListingService {
path: string = 'notes';
  constructor(private storeHelper: StoreHelper, private apiService: ApiService) {}

  createNote(note: Note) {
    return this.apiService.post(this.path, note)
    .do(savedNote => this.storeHelper.add('notes', savedNote))
  }

  getNotes() {
    return this.apiService.get(this.path)
    .do(res => this.storeHelper.update('notes', res.data));
  }

  completeNote(note: Note) {
    return this.apiService.delete(`${this.path}/${note.id}`)
    .do(res => this.storeHelper.findAndDelete('notes', res.id));
  }
}


这是我的store.ts

export interface Note {
  color: string,
  title: string,
  value: string,
  id?: string | number,
  createdAt?: string,
  updatedAt?: string,
  userId?: string
}

export interface State {
  notes: Array<Note>
}

const defaultState = {
  notes: []
}

const _store = new BehaviorSubject<State>(defaultState);

@Injectable()
export class Store {
  private _store = _store;
  changes = this._store.asObservable().distinctUntilChanged()

  setState(state: State) {
    this._store.next(state);
  }

  getState(): State {
    return this._store.value;
  }

  purge() {
    this._store.next(defaultState);
  }
}


这是我的store-helper.ts

export class StoreHelper {
  constructor(private store: Store) {}

  update(prop, state) {
    const currentState = this.store.getState();
    this.store.setState(Object.assign({}, currentState, { [prop]: state }));
  }

  add(prop, state) {
    const currentState = this.store.getState();
    const collection = currentState[prop];
    this.store.setState(Object.assign({}, currentState, { [prop]: [state, ...collection] }));
  }

  findAndUpdate(prop, state) {
    const currentState = this.store.getState();
    const collection = currentState[prop];

    this.store.setState(Object.assign({}, currentState, {[prop]: collection.map(item => {
      if (item.id !== state.id) {
        return item;
      }
      return Object.assign({}, item, state)
    })}))
  }

  findAndDelete(prop, id) {
    const currentState = this.store.getState();
    const collection = currentState[prop];
    this.store.setState(Object.assign({}, currentState, {[prop]: collection.filter(item => item.id !== id)}));
  }
}


这是如何将服务注入到我的app.module提供程序index.ts中

import * as services from './services';
import { Store } from './store';

export const mapValuesToArray = (obj) => Object.keys(obj).map(key => obj[key]);

export const providers = [
  Store,
  ...mapValuesToArray(services)
];


和app.module

import { providers } from './index'
providers: [providers, AnimationService]


发布请求工作得很好,但get请求却不能。
这是我得到的错误:


  静态解析符号值时遇到错误。
  
  不支持函数调用。
  
  考虑使用对导出函数的引用(原始.ts文件中的位置3:33)替换函数或lambda,在D:/angular2/someapp/src/app/index.ts中解析符号mapValuesToArray,在D中解析符号提供者:/angular2/someapp/src/app/index.ts,在D:/angular2/someapp/src/app/index.ts中解析符号提供者,在D:/ angular2 / someapp / src / app / app中解析符号AppModule。 module.ts,在D:/angular2/someapp/src/app/app.module.ts中解析符号AppModule

最佳答案

AoT compiler无法静态分析您提供的服务,因为您正在使用Object.keys方法枚举它们。

您可以通过将导出添加到显式列出服务的./services.ts来解决该问题:

export const SERVICE_PROVIDERS = [
    ServiceOne,
    ServiceTwo,
    ServiceThree
];


您的导入将如下所示:

import { SERVICE_PROVIDERS } from "./services";
import { Store } from './store';

export const providers = [
  ...SERVICE_PROVIDERS,
  Store
];

10-07 19:35
查看更多