简体   繁体   English

Angular可重用组件

[英]Reusable component with Angular

I want to create a widget which displays the list of schools in the state. 我想创建一个显示该州学校列表的小部件。 It reads the list of schools from a json file and get refreshed every 5 minutes. 它从json文件读取学校列表,并每5分钟刷新一次。 This widget needs to be used outside the project as well. 该小部件也需要在项目外部使用。 I mean I should be able to use this widget in other project with minimal effort. 我的意思是我应该能够以最小的努力在其他项目中使用此小部件。 I am kinda new to angular. 我对棱角有点陌生。 Can I create such a custom component with angular? 我可以用angular创建这样的自定义组件吗?

Template: 模板:

<main-component>
<app-school-list>  </app-school-list>
</main-component>

HomeController.cs- HomeController.cs-

public List<Schools> GetSchools(int stateId){
_homeService.GetSchools(stateId);
}

You need to create a library then you can deploy it to NPM and consume it in different projects. 您需要创建一个库,然后可以将其部署到NPM并在其他项目中使用它。 Another solution is using polymer, you create your web component and deploy it to NPM and it can be used by different technologies like Angular, JS, React etc. web components are more generic than a angular library. 另一个解决方案是使用聚合物,您可以创建Web组件并将其部署到NPM,并且可以被Angular,JS,React等不同技术使用。Web组件比angular库更通用。

https://blog.angularindepth.com/creating-a-library-in-angular-6-87799552e7e5 https://blog.angularindepth.com/creating-a-library-in-angular-6-87799552e7e5

https://blog.angulartraining.com/create-your-own-libraries-with-angular-cli-7b434600bbb7 https://blog.angulartraining.com/create-your-own-libraries-with-angular-cli-7b434600bbb7

To poll an api you use an RxJs interval 要轮询api,请使用RxJs间隔

@Injectable({
  providedIn: 'root'
})
export class SchoolService {
  schools$ = interval(300000).pipe(switchMap(_ => this.http.get('api/schools')));

  constructor(private http: HttpClient) {}
}

and then in your component you can bind the schools to your template with the async pipe 然后在您的组件中,您可以使用异步管道将学校绑定到模板

schools$ = this.schoolService.schools$;

constructor(private schoolService: SchoolService) {}

and in your html 并在您的html中

<ng-container *ngFor="school in schools$ | async">
  {{school.name}}
<ng-container>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM