Angular 4.5如何从组件获取服务值并在模板及其他组件展示
解决Angular 4.5中服务调用结果不展示及跨模块组件使用问题
让我一步步帮你搞定这几个问题:
问题1:点击按钮后无法展示服务返回值
你的getService()方法只是调用了msalService.getProduct(),但没有把返回值存到组件的变量里,模板自然没法绑定展示。我们来修改Login组件和模板:
修改Login组件代码:
import { Component } from '@angular/core'; import { Location} from '@angular/common'; import { MsalService } from '../Services/msal.service'; @Component({ selector: 'auth-login', templateUrl: './Login.Template.html', styleUrls: ['./Login.Style.scss'], // 移除这里的providers,后续在模块层面统一提供服务 // providers: [MsalService] }) export class Login{ constructor( private msalService: MsalService){ } public pageTitle: string = "testing ....."; // 新增变量用来存储服务返回值 public productResult: string = ''; getService(): void{ // 将服务返回值赋值给组件变量,供模板绑定 this.productResult = this.msalService.getProduct(); } }
修改Login模板代码:
<div class="panel-heading">{{pageTitle}}</div> <a class="btn btn-link" (click)="getService()">Login</a> <!-- 新增元素展示服务返回值,用*ngIf控制只有有值时才显示 --> <div *ngIf="productResult" class="mt-2">服务返回值:{{productResult}}</div>
问题2:优化服务的提供方式
你现在在Login组件的providers数组里声明MsalService,会导致每个Login组件实例都会生成一个新的服务实例。如果需要全局单例的服务(大部分场景下的合理需求),应该把服务添加到它所在模块的providers数组中。
假设你的服务和Login组件都在SecurityModule里,修改该模块:
import { NgModule } from '@angular/core'; import { MsalService } from './Services/msal.service'; import { Login } from './login/login.component'; @NgModule({ declarations: [Login], // 声明Login组件 exports: [Login], // 导出Login组件,让其他模块可以引用使用 providers: [MsalService] // 在模块层面提供服务,确保全局单例 }) export class SecurityModule { }
问题3:修正跨模块使用Login组件的错误
你现在直接在LayoutModule的imports数组里导入Login组件,这是错误的——imports数组只能导入其他NgModule,不能直接导入组件。正确做法是导入包含Login组件的模块:
修改LayoutModule代码:
import { NgModule } from '@angular/core'; import { SecurityModule } from '../security/security.module'; // 导入包含Login组件的模块 @NgModule({ imports: [ SecurityModule ] // 导入模块后,就能在该模块的模板中使用<auth-login>组件了 }) export class LayoutModule { }
验证步骤
- 重启Angular开发服务器,确保所有修改生效
- 访问包含
<auth-login>组件的页面 - 点击"Login"按钮,就能看到"服务返回值:12 Apples"正常展示了
内容的提问来源于stack exchange,提问作者K.Z
相关产品推荐
相关产品推荐

