直接code
1:Angular cli 创建组件component
ng g component components\rightng g c wave 简写需要定位到根路径下即可创建组件Could not find an NgModule. Use the skip-import option to skip importing in NgModule. PS C:\myAngulrDemos\20240428demo\mydemo01\src> cd .. PS C:\myAngulrDemos\20240428demo\mydemo01> ng g component components\mynews CREATE src/app/components/mynews/mynews.component.html (21 bytes) CREATE src/app/components/mynews/mynews.component.spec.ts (626 bytes) CREATE src/app/components/mynews/mynews.component.ts (275 bytes) CREATE src/app/components/mynews/mynews.component.css (0 bytes) UPDATE src/app/app.module.ts (486 bytes) PS C:\myAngulrDemos\20240428demo\mydemo01>
2:Angular cli 创建服务 service
ng g service services\mydata
在Angular中,服务是一种可重用的、负责特定任务的独立功能单元,比如获取数据、分享数据或者处理业务逻辑等。下面是如何创建和使用服务的步骤,以Angular的最新实践为准:创建服务 1:使用 @Injectable 装饰器: 所有的服务都需要使用 @Injectable() 装饰器来标记,这允许Angular的依赖注入系统识别并使用这个服务,下面为ts code:import { Injectable } from '@angular/core';@Injectable({providedIn: 'root', // 这使得服务成为一个单例,并在根模块级别提供 })export class MyService {constructor() { }// 服务方法示例 getData(): any {// 实现数据获取逻辑 }}2:提供服务: 在上面的例子中,我们使用了 providedIn: 'root',这意味着服务会在根模块级别被提供,并且在整个应用程序中作为单例存在。如果你希望更细粒度地控制服务的生命周期,可以在模块的 providers 数组中声明服务。使用服务Service 2.1:注入服务: 要在组件、指令或其他服务中使用服务,你需要将其注入到构造函数中 ,下面为ts import { Component } from '@angular/core';import { MyService } from './my.service';@Component({selector: 'app-my-component',template: `<p>{{data}}</p>`,})export class MyComponent {data: any;constructor(private myService: MyService) { }ngOnInit() {this.data = this.myService.getData();}}
3:==== 父传子 使用 Input 装饰器
父 app-root:html <h1>app root组件</h1> <hr> <p>参数:ptocback, pfunctionback:函数带到子组件</p> <app-myparent [ptoc]="ptocback" [pfunction]="pfunctionback"></app-myparent> //子组件 <router-outlet></router-outlet>父:ts import { Component } from '@angular/core';@Component({selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css'] }) export class AppComponent {title = 'mydemo01';ptocback= "你好峰哥:"+Date.now().toLocaleString();pfunctionback(){alert("hello fengge");} }
子:app-myparent HTML <p>myparent works!</p> <h2>来自父组件的参数:{{ptoc}}</h2> <hr><app-mychild></app-mychild> <button (click)="pfunctionClick()">点击获取父组件的函数</button>子:ts import { Component, OnInit } from '@angular/core';import { Input } from '@angular/core'; // 使用 input 装饰器 加 字段参数来传值 ,引入 @Component({selector: 'app-myparent',templateUrl: './myparent.component.html',styleUrls: ['./myparent.component.css'] })export class MyparentComponent implements OnInit {@Input() ptoc: any; //这里要定义为any才行,接受来自父组件的数据 @Input() pfunction() { }constructor(private data01service: Dataservice01Service) { }ngOnInit(): void {}pfunctionClick() {this.pfunction();}}
4:=====子传父 使用 ViewChild装饰器
父 app-myparent:html <p>myparent works!</p> <hr> <app-mychild #childData></app-mychild> <button (click)="childDatatoParentClick()">点击获取子传父的数据</button>父:ts import { Component, OnInit } from '@angular/core'; import { ViewChild } from '@angular/core';@Component({selector: 'app-myparent',templateUrl: './myparent.component.html',styleUrls: ['./myparent.component.css'] })export class MyparentComponent implements OnInit {@ViewChild("childData") childata: any;getChildData: any="";constructor() { }ngOnInit(): void {}childDatatoParentClick(){this.getChildData = this.childata.cNamealert("c->p:" + this.getChildData);} }
子 app-mychild:html <p>mychild works!</p>子 app-mychild:tsimport { Component } from '@angular/core'; @Component({selector: 'app-mychild',templateUrl: './mychild.component.html',styleUrls: ['./mychild.component.css'] }) export class MychildComponent implements OnInit {cName:any;constructor() { }ngOnInit(): void {this.cName = "我是Child组件的数据参数";}}
5:===组件使用Service服务传值或者获取数据
1:生成组件的命令 : ng g service services\mydataService01服务service ts code import { Injectable } from '@angular/core';@Injectable({providedIn: 'root' }) export class Dataservice01Service {constructor() { }getData(){return "this Data from service 01";} }
组件上使用 html <button (click)="getdata01serverClick()">点击获取服务上的数据</button>\组件ts import { Component, OnInit } from '@angular/core'; import { Dataservice01Service } from 'src/app/services/dataservice01.service'; //引入服务service @Component({selector: 'app-myparent',templateUrl: './myparent.component.html',styleUrls: ['./myparent.component.css'] })export class MyparentComponent implements OnInit {constructor(private data01service: Dataservice01Service) { //注入service 服务 }ngOnInit(): void {}getdata01serverClick() {let ds = this.data01service.getData();alert("来自服务的数据:" + ds);}}
6:子传父 使用 @Output装饰器
步骤 1: 在子组件中定义输出属性
1.1:创建事件发射器: 在子组件类中,使用@Output()装饰器定义一个事件发射器。通常,我们会使用EventEmitter作为其类型,它能够发射任何类型的数据,
1.2:在这个例子中,我们定义了一个名为messageEvent的输出属性,类型为EventEmitter<string>,意味着它可以发射字符串类型的数据
子ts code: import { Component, Output, EventEmitter } from '@angular/core';@Component({selector: 'app-child',template: `<button (click)="sendMessage()">发送消息给父组件</button>` }) export class ChildComponent {@Output() messageEvent = new EventEmitter<string>();sendMessage() {this.messageEvent.emit("Hello from Child!");} }
步骤 2: 在父组件模板中绑定事件
2.1:使用事件绑定: 在父组件的HTML模板中,通过事件绑定语法(())将子组件的输出事件与父组件中的一个方法绑定起来。
<!-- 父组件模板 --> <app-child (messageEvent)="receiveMessage($event)"></app-child> <p>{{ receivedMessage }}</p>
步骤 3: 在父组件类中处理事件
3.1:定义处理方法: 在父组件的类中,定义一个方法来接收并处理从子组件传来的数据 import { Component } from '@angular/core';@Component({selector: 'app-parent',templateUrl: './parent.component.html' }) export class ParentComponent {receivedMessage: string;receiveMessage(message: string) {this.receivedMessage = message;} }
7 最后来一张测试截图