Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Angular编写简单服务_Angular - Fatal编程技术网

用Angular编写简单服务

用Angular编写简单服务,angular,Angular,我是Angular框架的新手,我将创建一个简单的服务。它将从远程api获取数据-照片和名称。到目前为止,我有一个工作获取示例: const div=document.getElementById('author'); 常量url=https://randomuser.me/api/?results=1'; var f=fetch(url); f、 然后(完成),然后(建造); 功能已完成(响应){ 返回response.json(); }; 功能建设(数据){ var author=data.

我是Angular框架的新手,我将创建一个简单的服务。它将从远程api获取数据-照片和名称。到目前为止,我有一个工作获取示例:

const div=document.getElementById('author');
常量url=https://randomuser.me/api/?results=1';
var f=fetch(url);
f、 然后(完成),然后(建造);
功能已完成(响应){
返回response.json();
};
功能建设(数据){
var author=data.results[0];
var img=document.createElement(“img”);
img.src=author.picture.medium;
var p=document.createElement(“div”);
p、 innerHTML=author.name.first+''+author.name.last;
document.getElementById('author').append(img,p);
}

我会帮忙的

这是服务

    import { Injectable } from '@angular/core';

    @Injectable()
    export class DataFetchService {

      constructor(private http: HttpClient) { }
      getData() {
       return this.http.get('https://randomuser.me/api/?results=1')
      }

    }
和组件

  export class yourComponent {
      author;
      constructor(private dataFetch: DataFetchService) { }
      ngOnInit() {
        this.dataFetch.getData()
          .subscribe(res => this.author = res.results[0])   
      }

    }
加上一个模板

<img src="{{author.picture.medium}}">
<p> {{author.name.first}} {{author.name.last}}</p>

{{author.name.first}{{author.name.last}}

事实上,你们需要导入一些工作人员,但ide会帮助你们,并将服务注册到应用模块中。我认为这个问题只是为了概念上的证明。
希望能有所帮助。

我想知道什么是服务类,什么是组件类和模板。我知道你想要什么,但这不是这个网站的目的。我建议您阅读angular.io网站上的介绍和教程,它们写得很好。在这里反覆说明角度是如何工作的是没有意义的,这不是目的。另请参见。如果您陷入困境,请回来问一个具体问题,并提供所有相关信息。到那时,社区会非常乐意提供帮助。所以你的回答对我来说毫无用处。我已经在复习教程几天了。如果对我来说很清楚的话,我永远不会问这个问题,还有什么更具体的问题要问?我需要关于划分代码的建议,我使用Angular CLI,因此它可能会自动注册所有内容。这很有帮助,我将尝试注意Angular CLI不会自动注册服务,除非您使用
-m
标志并指定要在其中注册的模块。这很可能是因为服务可以在模块或组件中注册,而CLI无法假定您要使用哪种服务。