在我的component1.ts中,
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中编写具有不同查询参数的相同函数
因此,不必再次编写相同的函数n。我正试图为此编写可共享的服务,但介于两者之间。
@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中使用
答案 0 :(得分:0)
您可以使用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();
答案 1 :(得分:0)
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的提供程序中声明服务。