Gay*_*tne 3 typescript angular-services angular
我想知道如何使用路由器在两个组件之间传递数据。下图是我的组件视图的屏幕截图。
当我单击“查看报告”按钮时,我需要使用每个报告的数据“调用”另一个组件。
下面几行代码是调用查看报表按钮的方法viewFuelReport();它会在新选项卡中打开另一个包含数据的组件。
<button type="button" (click)="viewFuelReport()" class="btn btn-success">
View report
</button>
Run Code Online (Sandbox Code Playgroud)
viewFuelReport(){
this.router.navigate([]).then(result => {
window.open("/pages/view-report", "_blank");
});
}
Run Code Online (Sandbox Code Playgroud)
如何使用 Angular 中的路由器将数据从一个组件传递到另一个组件?
小智 6
如果您想将子组件的数据共享给父组件,可以使用@Output()和EventEmitter<>。
或者,如果您尝试在两个不相关的组件之间共享数据,您可以BehaviorSubject()通过Service;使用 这也适用于在父组件和子组件之间共享数据。
@Output()和共享数据EventEmitter<>。import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
Message: {{ message }}
<app-child (messageEvent)="receiveMessage($event)"></app-child>
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent{
constructor(){}
message: string;
receiveMessage($event){
this.message = $event
}
}
Run Code Online (Sandbox Code Playgroud)
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<button (click)="sendMessage()">Send message</button>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent{
message: string = "Hola, Mundo!";
@Output() messageEvent = new EventEmitter<string>();
constructor(){}
sendMessage(){
this.messageEvent.emit(this.message);
}
}
Run Code Online (Sandbox Code Playgroud)
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class DataService{
private messageSource = new BehaviorSubject('Original
message.');
currentMessage = this.messageSource.asObservable();
changeMessage(message: string){
this.messageSource.next(message)
}
}
Run Code Online (Sandbox Code Playgroud)
import { Component, OnInit } from '@angular/core';
import { DataService } from
'src/app/shared/services/data.service';
@Component({
selector: 'app-home',
template: `
{{ message }}
`,
styleUrls: ['./sibling.component.css']
})
export class HomeComponent implements OnInit{
message: string;
constructor(private dataService: DataService){}
ngOnInit(){
this.dataService.currentMessage.subscribe(message =>
this.message = message)
}
}
Run Code Online (Sandbox Code Playgroud)
import { Component, OnInit } from '@angular/core';
import { DataService } from
'src/app/shared/services/data.service';
@Component({
selector: 'app-about',
template: `
{{ message }}
<button (click)="newMessage()">New message</button>
`,
styleUrls: ['./sibling.component.css']
})
export class AboutComponent implements OnInit{
message: string;
constructor(private dataService: DataService){}
ngOnInit(){
this.dataService.currentMessage.subscribe(message =>
this.message = message)
}
newMessage(){
this.dataService.changeMessage('Hello from the About
component!')
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4401 次 |
| 最近记录: |