【问题标题】:How to properly use Cloud Functions into Angular component?如何在 Angular 组件中正确使用 Cloud Functions?
【发布时间】:2018-08-16 23:06:54
【问题描述】:

我在 Firebase 上创建了一个云函数,并尝试对其执行 POST 方法。 我应该如何将此功能触发到 Angular 组件中?

这是我所做的:

  const url = 'my-cloud-function-url';
  const params: URLSearchParams = new URLSearchParams();

  params.set('id', this.id);

  this.http.post(url, params)
      .toPromise()
      .then(res => {
          console.log(res);
       })
       .catch(err => {
          console.log(err);
       });

所以这段代码可以工作,但是 POST 方法不接受参数中的参数。我知道我可以更改 url 以在其中添加参数,但我很确定这是肮脏的方法。

感谢您的帮助!

【问题讨论】:

    标签: angular firebase google-cloud-functions angularfire


    【解决方案1】:

    https://angular.io/tutorial/toh-pt6#enable-http-services

    简而言之, 创建调用 http post/get 函数的服务。 当一个组件需要数据时,它会使用如下服务:

    sms.service.ts

    import {Injectable} from '@angular/core';
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import 'rxjs/add/operator/map';
    
    const BASE_API_URL = 'http-url';
    const httpOptions = {
        headers: new HttpHeaders({ 'Content-Type': 'application/json' })
    };
    
    @Injectable()
    export class SmsService {
    
        constructor(public http: HttpClient){}
    
        sendSms(sms){
            return this.http.post(BASE_API_URL+'/sms/send', JSON.stringify(sms), httpOptions);
        }
    
    }
    

    common.container.ts

    import {Component, OnInit} from '@angular/core';
    import {SmsService} from '../../services/sms.service';
    
    @Component({
        selector: 'app-common',
        styleUrls: ['common.container.css'],
        templateUrl: 'common.container.html'
    })
    
        export class CommonContainerComponent {
    
        public number;
        public smsMessage;
    
        constructor(public smsService: SmsService) {}
    
        sendSms(number, message) {
    
            const sms = {
                receiver : number,
                context : message
            };
    
            this.smsService.sendSms(sms).subscribe(
                results => {
                    console.log('sendSms results : ', results);
                },
                error => {
                    console.log('sendSms error : ', error);
                },
                () => {
                    console.log('sendSms completed');
                }
            );
        }
    }
    

    【讨论】:

    • 谢谢!这就是我正在寻找的:D
    猜你喜欢
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    • 2019-07-26
    • 2019-06-20
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    相关资源
    最近更新 更多