繁体   English   中英

如何通过Angular中的路由在Cloud Functions中对Cloud Firestore执行添加?

[英]How can I execute an add to Cloud Firestore in Cloud Functions through routes in Angular?

我正在尝试通过使用以下代码在Cloud Firestore数据库中创建文档:

后端:

index.js:

const express = require('express');
const chatrooms = express();
chatrooms.use(cors);
let chatroomsEndpoint = require('./chatroomsEndpoint')

chatrooms.post('/', chatroomsEndpoint.createChatroom); // Create new chatroom
exports.chatrooms = functions.https.onRequest(chatrooms);

chatroomsEndpoint.js:

const db = admin.firestore();
const chatroomsCollection = db.collection("chatrooms");

exports.createChatroom = function (req, res) {
    chatroomsCollection.add(req.body)
    .then(resul => {
        console.log('Successfully added chatroom');
        return res.status(201).send(true);
    })
    .catch((error) => {
        console.log('Error creating new chatroom', error)
        return res.send(false);
    })
}

前端:

chat.service.ts:

import { HttpClient } from '@angular/common/http';

constructor(
    private authService: AuthService,
    private http: HttpClient,
    private router: Router
  ) {
    this.headers.append('Content-Type', 'application/json');
  }

async create() {
    const userA = 'FeuzErzVIfTXKVvuagBzLvGcETK2'; 
    const userB = 'jmYZlOIjQkbOPnlVt54cfsdvJFb2';

    const data = {
      userA,
      userB,
      createdAt: Date.now(),
      messages: []
    };
    await this.http.put(`${this.apiUrl}/chatrooms`, data);
    return   this.router.navigate([`chats/XvlQIXo650VFhjMsOlf5`]) && console.log('return is executed');
  }

聊天室,list.component.html:

<button class="button is-info" (click)="chatService.create()">Create New Chat</button>

我的问题是,单击“创建新聊天”按钮后,我只得到console.log(执行“返回”)并导航到“聊天/ XvlQIXo650VFhjMsOlf5”,但是在Firestore中未创建任何文档,而我的Function却没有被触发。

客户端也没有错误,Firebase控制台也没有错误(在功能/日志下)。 我只想尝试使用路线创建文档。 我试图在其他帖子上寻求帮助,但我什至不确定自己遇到了哪种问题。

如果您只想通过应用程序使用云功能,我建议您看一看https.onCall云功能,您可以直接从Angular App进行调用。

请参考以下链接: https : //firebase.google.com/docs/functions/callable

如果您使用的是AngularFire包,则可以使用包中的httpsCallable方法调用onCall函数。

我找不到您上面的代码无法正常工作的原因。 您是否正在使用https包调用该函数? 您能否提供HTTP调用的错误或日志?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM