簡體   English   中英

無法通過Angular2和Firebase數據庫執行REST獲取請求

[英]Can't do a REST get request with Angular2 and Firebase database

我正在嘗試對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編譯器無法靜態分析您提供的服務,因為您正在使用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
];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM