Angular 使用服务在组件之间传递对象

Angular 使用服务在组件之间传递对象,angular,Angular,我在几页中读到,在进行路由时,在组件之间传递对象的最佳方式是使用服务 我依赖于最后一个示例(),并编写了以下代码来解决问题: 服务: @Injectable() export class tableService { public category: Category; } 构成部分1: export class tableComponent { categorys: Category[] = []; category: Category; passItemCat

我在几页中读到,在进行路由时,在组件之间传递对象的最佳方式是使用服务

我依赖于最后一个示例(),并编写了以下代码来解决问题:

服务:

@Injectable()
export class tableService {

    public category: Category;
}
构成部分1:

export class tableComponent {
    categorys: Category[] = []; 
    category: Category;

passItemCat(event: any) {
    this.category = {
        Code: "09",
        Attachments: [],
        Description: "eee",
        Response: {
            Destination: "",
            HtmlText: "",
            Text: "",
            Type: "",
        },
        Taxonomy: "ddd",
     }
    event.preventDefault(); 
}


constructor(public _tableService: tableService) { }

ngOnInit(): void {
    //get API for categorys
}

ngOnDestroy() {
    this._tableService.category = this.category;
}
}
模板组件1

<tr *ngFor="let item of categorys">
            <td>
                <nav>
                    <button routerLink="/ModifyCategory" routerLinkActive="active" class="btn btn-warning" (click)="passItemCat($event)">Modify</button>
                </nav>
            </td>
该问题发生在组件2的OnInit中,它在这个。\ u tableService.category中找不到元素


在这一步中(我以小步进行学习),单击使用静态类别,随后我想阅读组件模板1的项目。如果你想提出一些改进建议,我们会全神贯注。

这可能是因为
modifyCategoryComponent
tableComponent
之前读取
\u tableservice.category

如果改用
可观察的
,则在设置或更新值时,接收组件会收到通知

@Injectable()
export class tableService {
  private category:BehaviorSubject<Category> = new BehaviorSubject<Category>(null);
  get $category() {
    return this.category.asObservable();
  }
  setCategory(value:Category) {
    this.category.next(value);
  }
}
订阅类别更改

ngOnInit() {
    this._tableService.$category.subscribe(value => this._tableService.category = value);
}

另请参见

请原谅我的无知,但如果你能解释它是如何工作的,我就无法理解。对不起,我不理解你的评论。“不能构建ngOnInit”是什么意思?解释一下它是如何工作的“?我的意思是ngOnInit给我错误并阻止生成ts文件。我指的是订阅类别更改,因为:$category不存在于组件2中;不知道该解释什么。它允许以可观察的方式访问主题。你可以查看我答案中的链接以了解其他示例。对不起。您在哪里提供
表服务
?好的!问题是提供。。。appcomponet和第一个组件中都有一个提供。我从第一个组件中删除了提供并轻松地传递了它!!
ngOnDestroy() {
  this._tableService.setCategory(this.category);
}
ngOnInit() {
    this._tableService.$category.subscribe(value => this._tableService.category = value);
}