简体   繁体   English

Angular 4将服务从路线传递到组件

[英]Angular 4 passing a service to a component from routes

I have an Angular 4 application. 我有一个Angular 4应用程序。 I have a service that fetches some data from an API and I have a component that should display it. 我有一个从API提取一些数据的服务,并且我有一个应该显示它的组件。 I don't know how to pass the service as an argument to the component. 我不知道如何将服务作为参数传递给组件。 Any help will be profoundly appreciated. 任何帮助将不胜感激。 This is the best I managed: 这是我管理的最好的:

import {
  Component,
  OnInit
} from '@angular/core';

import { Title } from './title';

@Component({
  selector: 'home',
  providers: [
    Title
  ],
  styleUrls: [ './home.component.css' ],
  templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
  constructor(

  ) {}

  people: Person[] = [];

  ngOnInit(){
    peopleService
      .getAll()
      .subscribe(p => this.people = p)
  }
}

I've come across this article which shows how to pass arguments to components, but in my case no component contains HomeComponent, but it's only registered in the routes: 我看过这篇文章该文章显示了如何将参数传递给组件,但是在我的情况下,没有组件包含HomeComponent,但是它仅在路由中注册:

import { Routes } from '@angular/router';
import { HomeComponent } from './home';
import { AboutComponent } from './about';
import { NoContentComponent } from './no-content';

export const ROUTES: Routes = [
  { path: '',      component: HomeComponent },
  { path: 'home',  component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'detail', loadChildren: './+detail#DetailModule'},
  { path: 'barrel', loadChildren: './+barrel#BarrelModule'},
  { path: '**',    component: NoContentComponent },
];

To be able to use a service in a component, you must inject it. 为了能够在组件中使用服务,必须injectinject Otherwise Angular doesn't know what it is and where to look for it. 否则,Angular不知道它是什么以及在哪里寻找它。

To keep it simple you should add your service in your app.module.ts file. 为了简单app.module.ts您应该将service添加到app.module.ts文件中。 In the @NgModule object, add your peopleService to the providers key. @NgModule对象,添加peopleServiceproviders的关键。 Something like this. 这样的事情。

providers: [
  PeopleService
],

Make sure that your PeopleService is imported on top of that file of course. 当然,请确保将PeopleService导入到该文件的顶部。

Then in your HomeComponent you'll need to inject the service via the constructor . 然后,在HomeComponent您需要通过constructor注入服务。

export class HomeComponent implements OnInit {
  people: Person[] = [];

  constructor(private peopleService: PeopleService) {
  }

  ngOnInit(){
    this.peopleService
      .getAll()
      .subscribe(p => this.people = p)
    }
}

If you would like to read up on DI, this is a very useful blog post Dependency injection in Angular 如果您想阅读DI,这是一个非常有用的博客文章Angular中的依赖注入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM