freeapiservice是我的Web服务,我想在其中调用函数
我想在app.component
函数中使用另一个类insertFormadata
从app.component
调用参数:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpParams } from '@angular/common/http';
@Injectable()
export class freeApiService {
constructor(private httpclient: HttpClient) {
}
insertFormadata(): Observable<any> {
return this.httpclient.get("/api/api?type=savedata&fname=nilesh&tfvalue=js&mobile=6547896541&type_sec=1452&city=bhopal&email=nkardate@gmail.com")
}
getcomments(): Observable<any> {
return this.httpclient.get("http://jsonplaceholder.typicode.com/posts/1/comments")
}
getcommentsbyparameters(): Observable<any> {
let params1 = new HttpParams().set("userId", "1");
return this.httpclient.get("http://jsonplaceholder.typicode.com/posts", { params: params1 })
}
}
app.component.ts
文件代码,onSubmit
单击“我有JSON.stringify(this.data.name)
这个值,我想传递给Web服务api。
import { Component } from '@angular/core';
import { freeApiService } from './services/freeapi.service';
import { Comments } from './classes/comments';
import { from } from 'rxjs';
import { Posts } from './classes/posts';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'applykaroo';
data: any = {};
onSubmit() {
alert(JSON.stringify(this.data.name));
this._freeApiService.insertFormadata().subscribe(
data => {
this.lstcomments = data;
}
);
}
constructor(private _freeApiService: freeApiService) {
}
lstcomments: Comments[];
lstparacomments: Posts[];
ngOnInit() {
this._freeApiService.getcomments().subscribe(
data => {
this.lstcomments = data;
}
);
this._freeApiService.getcommentsbyparameters().subscribe(
data => {
this.lstparacomments = data;
}
)
}
}
答案 0 :(得分:1)
您的服务方法应如下:
insertFormadata(name: string): Observable<any>{
,您应该致电:
this._freeApiService.insertFormadata(this.data.name).subscribe(
有关功能和参数的更多信息,您可以找到here
答案 1 :(得分:0)
您的服务函数应接受参数。
insertFormadata(data: any): Observable < any > {
return this.httpclient.get("/api/api?type=savedata&fname=nilesh&tfvalue=js&mobile=6547896541&type_sec=1452&city=bhopal&email=nkardate@gmail.com")
}
您的app.component应该将参数传递给method。
this._freeApiService.insertFormadata(this.data).subscribe(data=>{this.lstcomments=data; });
注意:理想情况下,要保存数据,应使用http POST调用。
freeapiservice中类似如下的内容
insertFormadata(data:any):Observable<any>{
return this.httpclient.post("apiurl", data)
}