如何将常量从组件传递到服务并发出http请求[重复]

问题描述 投票:0回答:3

这个问题在这里已有答案:

好吧我正在尝试做的是我有一个*ngFor填充类别名称我正在尝试做的是获取用户点击的那个然后用它进行API调用但是当我点击按钮时没有任何反应。有没有办法将const传递给我的api.service,或者我在组件中执行此操作的方式是实现此目的的唯一方法。

section: string;

sectionlink(text: any): void {
   this.section = text;
   const endpointlist = 'https://api.nytimes.com/svc/books/v3/lists/{{this.section}}?api-key=my-key-here';
   return this.http.get<Listmodel[]>(endpointlist);
   console.log(this.section);
}
<li class="uk-active"><button (click)="sectionlink(section.list_name)">{{section.list_name}}</button></li>
html angular typescript
3个回答
0
投票

是的,您可以直接从组件中检索API调用结果,如Antoine所示。但是,随着您的应用程序的增长,您的组件也会增长,因此最好将API调用放在单独的服务中,如下所示:

import {HttpClient} from '@angular/common/http';

@Injectable({providedIn:'root'})
export class APIService {
    public static API_ENDPOINT = "https://api.nytimes.com/svc/books/v3/lists/";
    private static API_KEY = "IUOAHIUSYDFGOIAGHSFDOIHASDH"; // made up api key

    // the app will inject the HttpClient for you when this class is instantiated
    constructor(private http: HttpClient) {}

    // you can call this method whatever you like, as long as it makes sense
    public getBooks(text:string):Observable<ListModel[]> {
        return this.http.get<ListModel[]>(APIService.API_ENDPOINT + text + "?api-key=" + APIService.API_KEY);
    }
}

然后在你的组件中你可以调用这个方法:

// angular will inject your custom service here
constructor(private apiService: APIService) {} 

public sectionlink(text:string) {
    this.apiService.getBooks(text).subscribe(response => {
        console.log(response);
        // do whatever you need to do with response here
    });
}

不要忘记在你的模块中提供这个(只有当它是功能模块的一部分时; @injectable({providedIn:'root'})应该注意这一点):

@NgModule({
  declarations: [
     YourCustomComponent
  ],
  imports: [
    HttpClientModule
  ],
  providers: [APIService],
})
export class FeatureModule { }

2
投票

service.ts

getSectionlinks(text: string): Observable<Listmodel[]> {       
   const endpointlist = `https://api.nytimes.com/svc/books/v3/lists/${text}?api-key=7W3E72BGAxGLOHlX9Oe2GQSOtCtRJXAt`;
   return this.http.get<Listmodel[]>(endpointlist);
}

component.ts

sectionlink(text: string){
    this.service.getSectionlinks(text).subscribe(response =>  this.sectionData = response);
}

HTML

<li class="uk-active">
   <button (click)="sectionlink(section.list_name)">{{section.list_name}}< /button>
</li>

1
投票

假设您在函数中发送的文本有效,您可以执行以下操作。

sectionlink(text: string): void {
    const endpointlist = 'https://api.nytimes.com/svc/books/v3/lists/' + text + '?api-key=7W3E72BGAxGLOHlX9Oe2GQSOtCtRJXAt';
    this.http.get<Listmodel[]>(endpointlist).subscribe(result => {
        console.log(result);
    });
}

这将调用您的API并订阅结果。有关HttpClient的更多信息,请查看文档here

© www.soinside.com 2019 - 2024. All rights reserved.