angular - 无法将数据从服务传递到 Angular 中的组件
问题描述
我正在尝试将数据从我的服务传递到我的组件,但无法这样做。以下是来自服务和组件的代码:
authService.service.ts
import { Injectable } from '@angular/core';
import { HttpHeaders } from '@angular/common/http';
import{Http, RequestOptions,Headers} from '@angular/http'
import { Observable} from 'rxjs';
import { URLSearchParams,Response } from '@angular/http';
@Injectable()
export class AuthenticationService
{
constructor(private http: Http) { }
username:string = 'Admin';
password:string='livelink';
result :any;
login()
{
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('Username', this.username);
urlSearchParams.append('Password', this.password);
return this.http.post('http://localhost/otcs/cs.exe/api/v1/auth',urlSearchParams)
.subscribe((res:Response) =>
{
const data = res.json();
let headers = new Headers({
'OTCSTICKET': data['ticket']
});
let request_options = new RequestOptions({ headers:headers});
return this.http.get("http://localhost/otcs/cs.exe/api/v1/nodes/16236/output",request_options)
.subscribe(data =>
{
const report = data.json();
this.result = report;
console.log(this.result);
},
err => {
console.log(err);
}
)});
}
}
应用组件
import { Component } from '@angular/core';
import { AuthenticationService } from './authNew.servive';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import{Http, RequestOptions,Headers} from '@angular/http'
import { Observable} from 'rxjs';
import { URLSearchParams,Response } from '@angular/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent
{
constructor(private authenticationservice:AuthenticationService)
{
this.authenticationservice.login().subscribe(res:Response =>
{
//somecode
}) ;
}
}
问题是当我尝试订阅 AppComponent 时,出现以下错误:
我知道我在这里做了一些非常愚蠢的事情。此外,我尝试在我的服务中使用地图而不是订阅 POST 和 GET 调用,但在这种情况下,我收到如下所示的错误:
我正在导入'rxjs/add/operator/map';尝试使用地图时仍然出现错误,因此我考虑在服务本身内订阅,但这也无济于事。请帮助我了解如何对其进行排序并从我的服务中获取数据以在 AppComponent 中可用。
谢谢 !
解决方案
您在服务和组件中订阅了两次。
您在官方教程中应该如何管理这种情况:
简历是你应该在你的服务中得到可观察的
return this.http.get("http://localhost/otcs/cs.exe/api/v1/nodes/16236/output",request_options);
并管理组件中的订阅:
this.authenticationservice.login().subscribe(res:Response =>
{
//somecode
}) ;
推荐阅读
- typescript - Express SSE - 向会话用户广播
- c++ - Eigen 在不存储中间结果时给出错误的结果
- java - 当TUIO基准进入处理中的目标框时,如何使TUIO基准将背景更改为不同的图像?
- vega - 在 vega 中刷/链接(不是 vega-lite)
- java - “Java 方法是元数据”是什么意思?
- objective-c - 应用非标准电源断言和创建虚拟 HID
- python-3.x - python以不同的顺序打印字典
- node.js - 使用电子代理的 Nightmarejs
- java - 需要使用 IntelliJ 更改 GUI 上的背景,但背景隐藏了按钮
- c - Difference between array of pointers and pointer to array?