stenciljs中的http请求 [英] http requests in stenciljs

查看:51
本文介绍了stenciljs中的http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在StencilJS中发出http请求(GET/POST/PUT/DELETE)?

How can I make http requests (GET / POST / PUT / DELETE) in StencilJS?

我尝试如下使用axios:npm是否已安装axios --save ,并在模板组件中从导入axios?.一旦我调用 axios.get(...),我会收到以下错误消息:

I tried using axios as follows: Did npm install axios --save and in the stencil component import axios from 'axios';. As soon as I call axios.get(...)I get the following error message:

[错误]捆绑:node_modules/axios/lib/adapters/http.js,第4行:

[ ERROR ] bundling: node_modules/axios/lib/adapters/http.js, line: 4

模块无法导入自身

L3:var utils = require('./../utils');

L3: var utils = require('./../utils');

L4:变量结算= require('./../core/settle');

L4: var settle = require('./../core/settle');

L5:var buildURL = require('./../helpers/buildURL');

L5: var buildURL = require('./../helpers/buildURL');

我知道这可能与以下问题有关: https://github.com/ionic-team/stencil/issues/98

I understand it might have to do with this issue: https://github.com/ionic-team/stencil/issues/98

但是,有关如何获取html请求的任何建议都可以在模板组件中使用?

However, any recommendations on how to get html requests work within a stencil component?

推荐答案

我们可以使用 fetch API.它是浏览器本地的,因此不需要导入.StencilJS还具有一个polyfill,因此它可以在任何地方使用.

We can use the fetch API. It is browser native and does therefore not need an import. StencilJS also has a polyfill for it, so it works everywhere.

感谢@insanicae向我指出这一点.

Thanks to @insanicae for pointing me to it.

示例:

import { Component, State } from '@stencil/core';

@Component({
  tag: 'app-profile',
  styleUrl: 'app-profile.css'
})
export class AppProfile {
  @State() name: string;

  componentWillLoad() {
    fetch('https://api.github.com/users/ErvinLlojku')
      .then((response: Response) => response.json())
      .then(response => {
        this.name = response['name'];
      });
  }

  render() {
    return [
      <ion-header>
        <ion-toolbar color="primary">
          <ion-buttons slot="start">
            <ion-back-button defaultHref="/" />
          </ion-buttons>
          <ion-title>Profile: {this.name}</ion-title>
        </ion-toolbar>
      </ion-header>,

      <ion-content padding>
        <p>My name is {this.name}.</p>

      </ion-content>
    ];
  }
}

有关更多信息,请咨询fetch的官方文档. https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API

Consult official docs of fetch for more. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

这篇关于stenciljs中的http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆