【问题标题】:Update data using cloud function and angular使用云函数和角度更新数据
【发布时间】:2018-09-30 22:12:41
【问题描述】:

我是 firebase 环境的新手。 我想使用 Angular 服务使用云功能更新 Firebase 中的数据。 我可以使用云功能从 Firebase 获取角度数据,如下所示

readUsers(): Observable<Person[]>{
return this._http
.get(“https://us-central1-partner-f3f0b.cloudfunctions.net/getCustomer")
.map(res => res.json());
}

云功能如下

exports.getCustomer = functions.https.onRequest((req, res) => {
res.header(‘Content-Type’, ‘application/json’);
res.header(‘Access-Control-Allow-Origin’, ‘*’);
res.header(‘Access-Control-Allow-Headers’, ‘Content-Type’);
//respond to CORS preflight requests
if (req.method === ‘OPTIONS’) {
res.status(204).send(‘’);
}
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref(“customer”);
// Attach an asynchronous callback to read the data at our posts reference
ref.on(“value”, function (snapshot) {
console.log(snapshot.val());
res.status(200).json({ customer: snapshot.val() });
}, function (errorObject) {
console.log(“The read failed: “ + errorObject.code);
});
});

以下云功能正在运行并更新 firebase 数据库。

exports.getOneProducts = functions.https.onRequest((req, res) => {
res.header(‘Content-Type’, ‘application/json’);
res.header(‘Access-Control-Allow-Origin’, ‘*’);
res.header(‘Access-Control-Allow-Headers’, ‘Content-Type’);
//respond to CORS preflight requests
if (req.method === ‘OPTIONS’) {
res.status(204).send(‘’);
}
// Get a database reference to our posts
var db = admin.database();
var ref = db.ref(“/messages/-L82AfhFTr4odsh1GMId”);
ref.update({ original: “New trainer” });
});

我在这里面临的挑战是如何以角度 4 传递 json 格式的数据并使用谷歌云功能在 firebase 数据库中更新。 任何帮助表示赞赏。

【问题讨论】:

    标签: angular firebase google-cloud-functions


    【解决方案1】:

    您可以简单地将您的 JSON 放入您的请求的正文内容中(应该是一个 POST)并通过 req.body.xxxxx 在云函数中获取它

    例如如果您的请求正文内容是以下 JSON {original: “New trainer”},您将通过执行 req.body.original

    在您的函数中获得“New trainer”值

    【讨论】:

    • 额外问题:您为什么不使用网络库从网络客户端与 Firebase 交互? firebase.google.com/docs/database/web/start
    • 感谢您的回答。您能否指定如何以角度在正文中传递请求。您能否提供示例代码?
    • @BikramSao 恐怕不是......我不擅长 Angular。我个人使用 Vue.js,在这种特定情况下,我使用 Axios (github.com/axios/axios)。您将在示例部分中找到如何使用 Axios 发送 POST 请求。我在网上快速搜索“带有角度的 POST 请求”并找到了这个angular.io/guide/http#making-a-post-request:我猜你只需将数据声明为一个对象。
    猜你喜欢
    • 2015-06-26
    • 2016-08-05
    • 2020-12-17
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多