我正在尝试将数据从我的服务传递到我的组件,但无法这样做。以下是服务和组件的代码:
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中订阅时,我得到以下错误:
我知道我在做一些非常愚蠢的事情。此外,我尝试在我的服务中使用map而不是subscribe进行POST和GET调用,但在这种情况下,我得到如下所示的错误:
我正在导入' rxjs / add / operator / map&#39 ;;当我试图使用地图时,我仍然得到错误,因此我想在服务本身内订阅,但这也没有帮助。请帮助我理解如何对其进行排序并从我的服务中获取数据以便在AppComponent中使用。
谢谢!
答案 0 :(得分:0)
您在服务和组件中订阅了两次。
您在官方教程中应该如何管理此方案:
简历是你应该在你的服务中获得可观察的
return this.http.get("http://localhost/otcs/cs.exe/api/v1/nodes/16236/output",request_options);
并管理组件中的订阅:
this.authenticationservice.login().subscribe(res:Response =>
{
//somecode
}) ;