代码之家  ›  专栏  ›  技术社区  ›  Frost

如何正确地将云函数应用到角度分量中?

  •  2
  • Frost  · 技术社区  · 8 年前

    我在Firebase上创建了一个云函数,并尝试在其上执行POST方法。 我应该如何将这个函数触发为角度分量?

    以下是我所做的:

      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以在其中添加参数,但我很确定这是一个肮脏的方法。

    谢谢你的帮助!

    1 回复  |  直到 8 年前
        1
  •  6
  •   Jihoon Kwon    8 年前

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

    短暂地 创建调用http post/get函数的服务。 当组件需要数据时,它将使用如下服务:

    短信。服务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);
        }
    
    }
    

    常见的容器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');
                }
            );
        }
    }
    
    推荐文章