问题是我可以从一个组件中获取数据,然后将其传递给服务,但另一个组件无法从该服务中获取该数据。
这些组件是兄弟姐妹。
服务
import { Injectable } from '@angular/core';
@Injectable()
export class TodosService {
todo:string = ''
constructor() { }
insertTodo(todo: string) {
this.todo = '' + todo;
console.log(this.todo)
}
}
组件1(从中获取数据)
import { Component } from '@angular/core';
import { TodosService } from '../todos/todos.service';
@Component({
selector: 'app-todo-form',
templateUrl: './todo-form.component.html',
styleUrls: ['./todo-form.component.css']
})
export class TodoFormComponent {
constructor(private todosService: TodosService) {}
todo:string = ''
submitTodo() {
this.todosService.insertTodo(this.todo);
console.log('form ', this.todo)
this.todo = ''
}
}
HTML
<input type="text" [(ngModel)] = 'todo' (input)='submitTodo()'>
组件2(应获取数据的那个)
import { Component, OnInit } from '@angular/core';
import { TodosService } from '../todos/todos.service';
@Component({
selector: 'app-todo-list',
templateUrl: './todo-list.component.html',
styleUrls: ['./todo-list.component.css']
})
export class TodoListComponent implements OnInit {
todos:string[] = []
constructor(private todosService: TodosService) { }
ngOnInit() {
return this.todos.push(this.todosService.todo);
}
}
第二个组件中的todos数组始终为空
答案 0 :(得分:2)
我认为你应该使用rxjs主题
简化示例:
服务:
import { Injectable } from '@angular/core'
import { Subject } from 'rxjs/Subject'
@Injectable()
export class XTestService {
todo: Subject<string>
constructor() {
this.todo = new Subject<string>()
}
setTodo(t: string){
this.todo.next(t)
}
}
在第一个组件中,您应该设置数据(我在这里使用虚拟字符串,但您可以根据需要实现它)
组件1:
import { Component, OnInit } from '@angular/core'
import { XTestService } from './xtest.service'
@Component({
selector: 'xtest-cop',
template: `
<button type="button" (click)="submitTodo()" >Submit Todo</button>
`
})
export class XTestComponent {
constructor(private xservice: XTestService) { }
submitTodo() {
this.xservice.setTodo("dummy data")
}
}
并且您应该从您的服务订阅todo并等待数据:
组件2
import { Component, OnInit } from '@angular/core'
import { XTestService} from './xtest.service'
@Component({
selector: 'xtest2-cop',
template: `{{todo}}`
})
export class XTest2Component implements OnInit{
todo: string
constructor( private xservice : XTestService){}
ngOnInit():void{
this.xservice.todo.subscribe(value => {
this.todo = value
})
}
}
答案 1 :(得分:0)
在我看来,在调用方法submitTodo()之前,第二个组件ngOnInit()的初始化正在发生,因此该值永远不会被推送到第二个组件中的todo数组中。