如何使用服务从一个组件向另一个组件注入价值?
答案 0 :(得分:1)
您可以使用Subject
创建服务。并将其订阅为可观察。
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class InjectionService {
constructor() { }
private changeSubject = new Subject<any>();
changeEmitted$ = this.changeSubject.asObservable();
emitChange(data: {}) {
this.changeSubject.next(data);
}
}
答案 1 :(得分:1)
如果您的问题与使用服务进行组件通信有关,则可以尝试以下链接。
总是最好张贴您要解决的尝试代码或问题代码
https://www.dotnetcurry.com/angularjs/1445/angular-services-component-communication
https://medium.com/@enriqueoriol/angular-service-component-communication-4933782af52c
答案 2 :(得分:0)
假设您正在寻找单例服务以在整个应用程序中共享价值,请参见此处; https://angular.io/guide/singleton-services
以下是一个使用BehaviourSubject向感兴趣的组件发出更改的简单示例;
data.service.ts
import {BehaviorSubject} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
public sharedString = new BehaviourSubject<string>('default value');
constructor(private dataService: DataService) {
// Trigger an update from the DataService every 10 seconds. This could come from an API or open socket
setTimeout(() => dataService.sharedString.next('DataService 1 says hi'), 10000);
}
}
comp1.component.ts
Component({ })
export class Comp1Component {
// Inject data service into Comp1Component
constructor(private dataService: DataService) {
// Listen to changes
dataService.sharedString.subscribe((value) => {
console.log('Comp1Component::: ' + value);
});
// Trigger an update from the Comp1Component every 5 second. This could come from the user UI
setTimeout(() => dataService.sharedString.next('Component 1 says hi'), 5000);
}
}
comp2.component.ts
Component({ })
export class Comp2Component {
// Inject data service into Comp2Component
constructor(private dataService: DataService) {
// Get the current value
console.log('Comp2Component::: Current value:: ' + dataService.sharedString.getValue());
// Listen to changes
dataService.sharedString.subscribe((value) => {
console.log('Comp2Component::: ' + value);
});
// Trigger an update from the Comp2Component every 1 second. This could come from the user UI
setTimeout(() => dataService.sharedString.next('Component 2 says hi'), 1000);
}
}
答案 3 :(得分:0)
让我们考虑一下,有两个子组件和父组件,并且我们将在它们之间拥有称为公共数据服务的公共服务。
公共数据服务:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class CommonDataService {
private messageSource = new BehaviorSubject('Common data service');
currentMessage = this.messageSource.asObservable();
constructor() { }
changeMessage(message: string) {
this.messageSource.next(message)
}
}
上面的代码用于使用observable在两个组件之间创建通用服务。对于可观察到的,请通过this。
父项:
import { Component, OnInit } from '@angular/core';
import { CommonDataService } from "../common-data.service";
@Component({
selector: 'app-parent',
template: `
{{message}}
`,
})
export class ParentComponent implements OnInit {
message:string;
constructor(private data: CommonDataService) { }
ngOnInit() {
this.data.currentMessage.subscribe(message => this.message = message)
}
}
上面的代码从公共数据服务获取消息并显示在父组件视图上。
子组件:
import { Component, OnInit } from '@angular/core';
import { CommonDataService } from "../common-data.service";
@Component({
selector: 'app-sibling',
template: `
{{ oldMessage }}
<br>
{{ newMessage }}
`,
})
export class SiblingComponent implements OnInit {
OldMessage:string = "";
newMessage:string = "";
constructor(private data: DataService) { }
ngOnInit() {
this.data.currentMessage.subscribe(message => {
this.oldMessage = this.newMessage;
this.newMessage = message;
});
setInterval(
() => {
this.newmessage();
},
3000
);
}
newMessage() {
this.data.changeMessage(Math.random().toString(36).substring(7));
}
}
编写上述代码是为了每三秒钟在子组件中更新数字消息。由于公共数据服务是可观察的,因此由于已在已预订的ngOnInit
中预订了可观察的对象,因此父组件中的数据会自动更新。
答案 4 :(得分:0)
此示例使用@Injectable注释将服务注入另一个服务
帐户服务正在使用@Injectable()批注注入日志记录服务,并且 使用构造函数将帐户服务注入到app.component.ts中,并确保 在app.module.ts
的providers数组中添加服务
enter code here
//1. Account Service :
import { Injectable } from '@angular/core';
import { LoggingService } from './logging.service';
@Injectable()
export class AccountsService {
constructor(private loggingService: LoggingService) {}
}
// 2. Loggin Service :
export class LoggingService {
logStatusChange(status: string) {
console.log('A server status changed, new status: ' + status);
}
}
//3. Add it under providers array in app module
providers: [AccountsService, LoggingService],
bootstrap: [AppComponent]
//4. Finally app component is injecting account service
export class AppComponent implements OnInit {
accounts: {name: string, status: string}[] = [];
constructor(private accountsService: AccountsService) {}
ngOnInit() {
this.accounts = this.accountsService.accounts;
}
}