我有一个主题,其中有Resolve在服务文件中实现的接口,可以正常工作。我在做同样的方法,但是界面不起作用。我的意思是,当我在ts文件中对其进行初始化时,我需要服务中的products数组,这些数组中的数据来自我用来获取所有公司的api中的数组。
这是我的ts代码:
export class CompanyComponent implements OnInit {
dataSource: FilesDataSource | null;
displayedColumns = ['id', 'name'];
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild('filter') filter: ElementRef;
@ViewChild(MatSort) sort: MatSort;
companyData: any;
subscription: Subscription;
imageUrl = environment.imageUrl;
constructor(private companyService:CompanyService,private router: Router,private route: ActivatedRoute) { }
ngOnInit() {
this.dataSource = new FilesDataSource(this.companyService, this.paginator, this.sort);
fromEvent(this.filter.nativeElement, 'keyup').pipe(
debounceTime(150),
distinctUntilChanged()
).subscribe(() => {
if ( !this.dataSource )
{
return;
}
this.dataSource.filter = this.filter.nativeElement.value;
});
}
export class FilesDataSource extends DataSource<any>
{
}
}
这是CompanyService
@Injectable()
export class CompanyService implements Resolve<any>
{
baseUrl = environment.baseUrl;
token: string;
products: any[];
onProductsChanged: BehaviorSubject<any> = new BehaviorSubject({});
constructor(
private http: HttpClient,
private authService: AuthService
)
{
}
/**
* Resolve
* @param {ActivatedRouteSnapshot} route
* @param {RouterStateSnapshot} state
* @returns {Observable<any> | Promise<any> | any}
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any
{
return new Promise((resolve, reject) => {
Promise.all([
this.getProducts()
]).then(
() => {
resolve();
},
reject
);
});
}
getProducts(): Promise<any>
{
return new Promise((resolve, reject) => {
const token = this.authService.getToken();
this.http.get(this.baseUrl+'companies?access-token='+token)
.subscribe((response: any) => {
this.products = response;
console.log(this.products);
this.onProductsChanged.next(this.products);
resolve(response);
}, reject);
});
}
}
在这里,当我在company ts构造函数中初始化CompanyService时,在CompanyService中实现的解决方法无法正常工作。相同的方法在本地主题演示中也可以正常工作。我不知道代码中缺少什么。
答案 0 :(得分:0)
我已经完成了自己的工作。我不知道它如何传递数据。我所缺少的是我必须在这样的路由中添加它
{
path : 'company',
component: CompanyComponent,
resolve : {
data: CompanyService
}
},