【问题标题】:Angular Search better approachAngular Search 更好的方法
【发布时间】:2019-04-12 05:27:22
【问题描述】:

让我们假设,我有一个像

这样的组件层次结构
<app-component> 
<header></header>
<sidebar>
    <form-component>
</sidebar>
<sidebar />
    <breadcrum>
    <search-result />
</app-component>

此布局包含一个“左侧栏”,其中包含一个表单,用于根据姓名、年龄、性别等输入字段搜索“学生”。

包含搜索结果组件的右侧需要显示此更新的结果集。

我无法理解,在这种情况下如何将结果数据传递给“search-result”?

需要输入 1. 应用组件是否放置正确? 2. 如何在这些组件之间传递结果“学生”数据以显示结果?

PS:我知道@Input() 和@Output,但有点困惑如何使用“搜索结果”组件提供结果数据?

【问题讨论】:

  • 您应该使用服务在组件之间传递这些数据
  • 在侧边栏和搜索结果组件上方放置一个公共父组件。
  • 您评论了您如何知道输出装饰器。您可以使用此装饰器来设置事件发射器。您可以让此事件发射器将搜索结果发送到父组件(在本例中为 app-component)。然后您可以使用输入装饰器将变量从应用组件提供给搜索结果。

标签: angular html angular-components


【解决方案1】:

您可以使用类似架构的消息传递来实现这一点。每当侧边栏发生更改(可能是按键/搜索按钮单击)时,让其他组件知道此更改。这可以实现如下所示:

有如下图所示的服务:

DataService.ts:

@Injectable()
export class DataService{
private subject = new Subject<any>();
sendMessage(message: any) {
    this.subject.next({ obj: message });
}

clearMessage() {
    this.subject.next();
}

getMessage(): Observable<any> {
    return this.subject.asObservable();
}
}

sidebar.component.ts:

  this.dataservice.sendMessage(send the object that you would require in the other 
  component)

searchresult.component.ts

messagesubscription: Subscription;
constructor(private dataservice: DataService) {
  this.messagesubscription = this.dataservice.getMessage().subscribe((message) 
  => {
     if (message.obj) {
        // access the object here
     }
   });
}

【讨论】:

    猜你喜欢
    • 2019-11-04
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多