【发布时间】:2020-08-01 05:22:51
【问题描述】:
我正在创建一个 Deckbuilder,我有这些卡片组和一个 data-storage.service 来在 Firebase 中存储和获取卡片组。 我有一个组件卡组详细信息,它显示了选定卡组的详细信息,并允许将卡删除或添加到卡组。 我正在尝试将修改后的卡片存储在 firebase 中选定的牌组中
这是数据存储服务
@Injectable({ providedIn: "root" })
export class DataStorageService {
constructor(private http: HttpClient, private deckService: DeckService) {}
storeDecks() {
const decks = this.deckService.getDecks();
this.http
.put("https://ang-cards.firebaseio.com/decks.json", decks)
.subscribe((response) => {
console.log(response);
console.log("stored");
});
}
fetchDecks() {
return this.http
.get<Deck[]>("https://ang-cards.firebaseio.com/decks.json")
.subscribe((decks) => {
decks
? this.deckService.setDecks(decks)
: this.deckService.setDecks([]);
console.log("fetching", decks);
});
}
storeCards(i: number, cards: Card[]){
this.http
.put("https://ang-cards.firebaseio.com/decks/" + i + "/deckCards", cards)
.subscribe((response) => {
console.log(response);
console.log("cards stored");
});
}
}
storeDecks 和 fetchDecks 可以工作,但是我在 onCardsEdit() 函数的 deck-details 组件中调用的 storeCards 函数存在问题。 这是甲板细节组件
import { Card } from "./../../card/card.model";
import { Deck } from "./../../deck/deck.model";
import { Component, OnInit, Input } from "@angular/core";
import { DeckService } from "src/app/deck/deck.service";
import { ActivatedRoute, Params, Router } from "@angular/router";
import { Subscription } from "rxjs";
import { DataStorageService } from 'src/app/shared/data-storage.service';
@Component({
selector: "app-deck-details",
templateUrl: "./deck-details.component.html",
styleUrls: ["./deck-details.component.scss"],
})
export class DeckDetailsComponent implements OnInit {
paramsSubscription: Subscription;
id: number;
decks: Deck[];
deck: Deck;
constructor(
private deckService: DeckService,
private route: ActivatedRoute,
private dataStorageService: DataStorageService
) {}
ngOnInit() {
this.decks = this.deckService.getDecks();
this.id = this.route.snapshot.params["id"];
this.paramsSubscription = this.route.params.subscribe((params: Params) => {
this.id = params["id"];
this.deck = this.decks.find((deck) => deck.id === this.id);
});
}
onDeleteCard(i){
this.deckService.deleteCard(this.deck, this.deck.deckCards[i])
}
onCardsEdit(){
this.dataStorageService.storeCards(this.decks.indexOf(this.deck), this.deck.deckCards)
}
ngOnDestroy() {
this.paramsSubscription.unsubscribe();
}
}
当我尝试存储卡片时,出现以下 3 个错误:
从源“http://localhost:4200”访问位于“https://ang-cards.firebaseio.com/decks/1/deckCards”的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。
PUT https://ang-cards.firebaseio.com/decks/1/deckCards net::ERR_FAILED
core.js:5882 ERROR HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "https://ang-cards.firebaseio.com/decks/1/deckCards", ok: false, ...}
【问题讨论】:
-
您是否已经搜索过错误消息? CORS 政策相当频繁地弹出,因此很可能很好地解释了您为什么会得到它,以及如何解决它。如果我没记错,那是因为您忘记在 URL 末尾添加
.json。
标签: json typescript firebase firebase-realtime-database