简体   繁体   English

如何在 angular 6 的子组件中使用服务内部的方法

[英]How to use a method inside service in a child component in angular 6

In backend API some data is there.在后端 API 中有一些数据。 From front-end, i generate to get a request to read those backend data and show in front-end.从前端,我生成一个请求来读取这些后端数据并在前端显示。 For this, i created an Offer component and two child components of this offer component ie general & special component.为此,我创建了一个 Offer 组件和这个 Offer 组件的两个子组件,即通用和特殊组件。 I created one service, within that i created one method, inside the method i generate to get a request to connect with backend API.我创建了一个服务,在其中我创建了一个方法,在我生成的方法中以获取与后端 API 连接的请求。 Now when i am trying to import this service to that child component i am getting compilation to fail error in visual studio code saying "ERROR in app/offers/general/general.component.ts:2:30 - error现在,当我尝试将此服务导入到该子组件时,我在 Visual Studio 代码中遇到编译失败错误,提示“错误在app/offers/general/general.component.ts:2:30 - error

TS2307: Cannot find module '../event.service' TS2307:找不到模块“../event.service”

. . Now my question "how to use a service by a child component in the angular application"?现在我的问题是“如何通过 angular 应用程序中的子组件使用服务”? in general.component.ts ->在general.component.ts ->

 import { Component, OnInit } from '@angular/core'; import { EventService } from '../event.service'; @Component({ selector: 'app-general', templateUrl: './general.component.html', styleUrls: ['./general.component.css'] }) export class GeneralComponent implements OnInit { events = []; constructor(private _eventservice: EventService ) { } ngOnInit() { this._eventservice.showGeneralOffers().subscribe( res => this.events = res, err => console.log(err) ); } }

in event.service.ts ->在 event.service.ts ->

 import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class EventService { private _generalOffersUrl = 'http://localhost:3000/api/general'; private _specialOffersUrl = 'http://localhost:3000/api/special'; constructor(private http: HttpClient) { } getGeneralOffers() { return this.http.get<any>(this._generalOffersUrl); } getSpecialOffers() { return this.http.get<any>(this._specialOffersUrl); } }

Seems like issue with the importing service path.似乎是导入服务路径的问题。 (import { EventService } from '../event.service';). (从 '../event.service' 导入 { EventService };)。 Check given path is correct or not.检查给定路径是否正确。

It seems a simple path problem.这似乎是一个简单的路径问题。 Delete import of service in generalComponent costructor, go over EventService, a popup will come out, and click on quick fix, automatically will write the right path.在generalComponent costructor中删除service的import,过EventService,会弹出一个弹框,点击quick fix,自动会写到正确的路径。

你导入的相对路径不对,改成,

import { EventService } from './event.service';

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

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