在我的组件中,我有
ngOnInit(){this.query= "some text"; this.getProjectList(this.query);}
public getProjectList(query: object) {
this.appservice.search(this.query).then((response: any) => {
if (response) {
this.projects = response.results;
}
});
}
我需要在component2.ts中使用不同的查询参数编写相同的函数
所以不要再次再次编写相同的函数。我正试图为此编写可共享的服务,但卡在两者之间。
@Injectable()
export class ProjectService {
constructor(private appService: AppService){}
getProjectList(query: object) {
this.appService.search(query).then((response: any) => { // query param here need to updated
if (response) {
return response.results;?? // I don't know what should I write here
}
});
}
}
请告诉我如何在可共享服务中更新上述方法并在component1.ts和component2.ts中使用它
你可以使用switchMap。像这样的东西:
Observable.create((observer: any) => {
this.searchChangeObserver = observer;
}).pipe(
debounceTime(300),
distinctUntilChanged(),
map((value) => {
this.searchFilterValue = value;
this.query = { q: " some text" + this.searchFilterValue};
return query;
}),
switchMap((query) => this.appservice.search(query)),
tap((response) => this.projects = response.results;)
)
.subscribe();
The recommended pattern将使用您注入组件的共享服务。以下是一个简单的例子:
shared.service.ts
import { HttpClient } from '@angular/common/http';
@Injectable()
export class SharedService {
constructor(
private httpClient: HttpClient
) {}
searchSomething (someUrl) {
return this.httpClient.get(someUrl);
}
}
first.component.ts
import { SharedService } from '../../../core/services/shared.service';
@Component({
selector: 'first-component',
templateUrl: 'first.component.html',
styleUrls: ['first.component.scss']
})
export class FirstComponent implements OnInit {
constructor (
private sharedService: SharedService
) {}
ngOnInit(): void {
this.sharedService.searchSomething('exampleUrl.com').subscribe(result => console.log(result));
}
}
只需在第二个组件或第二个服务中执行相同操作,并且不要忘记在AppModule的提供程序中声明服务。