【问题标题】:Sending Variable from Component to Service in Angular 5在 Angular 5 中将变量从组件发送到服务
【发布时间】:2018-10-22 04:34:52
【问题描述】:

在我当前的 Angular 5 项目中,我一直在通过我的服务成功调用 API

(代码保持简洁)

myService.ts :

@Injectable()
export class my-service-service {

  constructor(private _http: HttpClient) {
   }

  myData1() {
    return this._http.get("API_URL")
      .map(result => result);
  }

并通过订阅上述服务访问有关我连接的组件的信息。

myComponent.ts:

   import { myServiceService } from './my-service-service.service';
    @Component({
    ...
    })

constructor(private router: Router,
    private route: ActivatedRoute,
    private _myData: myServiceService) {
   ...
   }

ngOnInit() {

 this._myData.myData1()
    .subscribe(res => {
//Able to access data successfully here 
     }
}

现在我希望从我的控制器向服务发送相反方向的数据。 例如假设我有

  public myVar: any;

我希望从我的服务中访问这个变量(也许将它动态附加到 API 调用中) 我应该继续这样做怎么样。

【问题讨论】:

    标签: angular service components angular5 web-development-server


    【解决方案1】:

    “从我的控制器向服务发送相反方向的数据”最好的方法是使用函数/方法参数。

    //service.ts
    myData1(parameter1) {
      //do whatever you need with parameter1
      return this._http.get("API_URL")
        .map(result => result);
    }
    
    
    //component.ts
    public myVar: any;
    ngOnInit() {
    
     this._myData.myData1(this.myVar).subscribe(res => { })
    }
    

    【讨论】:

    • 我想将数据从组件 A 的一个控制器发送到组件 B 的服务。我们应该怎么做?
    猜你喜欢
    • 2017-10-19
    • 2022-01-23
    • 2018-03-02
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 2018-08-22
    • 1970-01-01
    相关资源
    最近更新 更多