如何显示从Rails后端到Ember前端的数据,而不将其保存在数据库中并且不使用Ember-Data?

时间:2019-01-28 03:23:42

标签: ruby-on-rails ember.js ember-data

问题:

我已经使用rest-client通过我的Rails后端从newsapi.org中提取新闻文章。我可以在localhost:3000 / articles上显示该数据。我不想(不必要)将这些数据保存到数据库,并且想在Rails后端调用它之后在Ember前端简单地显示它。我收到此错误:

Error while processing route: article Assertion Failed: You must include an 'id' for article in an object passed to 'push'  

我理解这意味着我的数据没有“ id”,而实际上没有。我无法控制传入的数据。

{
  "status": "ok",
  "totalResults": 6868,
  "articles": [
{
  "source": {
    "id": "mashable",
    "name": "Mashable"
  },
  "author": "Lacey Smith",
  "title": "Cannabis may alter the genetic makeup of sperm",
  "description": "A new study suggests that marijuana use can not 
only lower sperm count, but also affect sperm DNA. Read more... More 
about Marijuana, Cannabis, Sperm, Science, and Health",
  "url": "https://mashable.com/video/cannabis-sperm-dna/",
  "content": null
},  

Ember-Data不喜欢它,因为它不是JSONAPI格式,因此我无法将其更改为JSONAPI。如何在不使用Ember-Data且不必将其保存到数据库的情况下在余烬前端显示此数据?我发现所有教程都有使用数据库和Ember-Data的示例。

我已经尝试过的方法:

我试图将其保存到我的数据库中并从那里加载,但是我认为这可能会使这个想法复杂化,因为我将需要抓取数据并将其保存到我的数据库中,并且事实证明这很难做到。我对后端的东西没有经验,也没有找到很多答案。如果您有这样做的答案,请随时在这里回答:

How to automatically save data from url to database

我愿意尝试一下。我本来以为这是最好的方法。我可以保存数据,并且仅在返回新文章时才将其添加到数据库中。我没有这种运气,所以我想我应该从另一个方向着手。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

如果要在ember-data之外进行某些处理,请创建一个service。在您的服务中,您将需要向后端发出ajax / fetch请求。假设您使用ember-ajax发出请求:

import Service, { inject } from '@ember/service';

export default Service.extend({
  // inject the ember-ajax ajax service into your service
  ajax: inject(),
  //this returns a promise
  getNewsItems(){
    var options = {
      // request options (aka anything needed to authenticate against your api, etc)
    };

    let url = "yourBackendEndpoint/for/this/resource";
    return request(url, options).then(response => {
      // `response` is the data from the server
      //  here you want to convert the JSON into something useable
      return response;
    });
  }
});

然后,在某个路径的模型挂钩中,您需要此服务(我们将在your-app/services/my-service.js中定义该服务)来获取新闻提要项:

import Route from '@ember/route';
import { inject } from '@ember/service';

export default Route.extend({
  myService: inject(),
  model(){
    let myService = this.get('myService');
    return myService.getNewsItems();
  }
)

我个人使用ember-fetch来避免jQuery依赖性,并且可以在我的应用程序的所有目标浏览器中使用。我没有在任何应用程序中使用余烬数据。