我有一个从GET请求中检索数据的服务,并将这些数据存储到我要传递给我的组件的两个变量中 - 我可以看到服务中的所有数据我只能在我的数据中检索到这些数据成分
当我在console.log()中调用this.sidebarService.getMenuItems()时,它返回undefined - 任何想法
//侧边栏服务
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { UserService } from '../../services/user.service';
@Injectable()
export class SidebarService {
menu: any;
menuItems: any;
menuCategories: any;
constructor(private http: HttpClient, private userService: UserService) {
getMenuItems() {
if (this.userService.getAuth() != null) {
this.http.get('https://dev.mysite.com/api/calendar/auth',
{ params: new HttpParams()
.set('token', this.userService.getAuth().__token)})
.subscribe(data => {
console.log('data', data);
if (data !== undefined) {
this.menuItems = (data.menuItems !== undefined) ? data.menuItems : [];
this.menuCategories = (data.menuCategories !== undefined) ? data.menuCategories : [];
}
});
}
}
}
//侧边栏组件
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { UserService } from '../../services/user.service';
import { SidebarService } from './sidebar.service';
@Component({
selector: 'app-sidebar',
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.scss'],
})
export class SidebarComponent implements OnInit {
menu: any;
menuItems: any;
menuCategories: any;
constructor(private http: HttpClient, private userService: UserService, private sidebarService: SidebarService) {
console.log('menuService', this.sidebarService.getMenuItems());
}
ngOnInit() {
}
objectKeys = function(obj) {
return Object.keys(obj);
}
}
答案 0 :(得分:1)
您没有从getMenuItems()
方法
你应该返回一个Observable:
...
return this.http.get('...