通过服务从角度组件调用mongodb

时间:2019-01-29 16:06:49

标签: node.js angularjs

我正在从组件调用服务。从服务中,我正在调用节点js api。

将从groups.service调用的Node.js api代码

app.get("/GetGroupDetails/:id", function (req, res) {
    dbo.collection("UserGroup").find({groupID: 
req.params.id}).toArray(function(err, result) {
        if (err) throw err;        
        console.log(result);
        res.send(result);
    });
})

Groups.service代码(此问题实例中未使用GetGroups)

import { Observable} from 'rxjs/observable';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Http, Response } from '@angular/http';

import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable({
  providedIn: 'root'
})
export class GroupsService {

  constructor(private http: HttpClient) { }

    GetGroups() {
      return this.http.get('http://localhost:2019/GetGroups');
    }

    GetGroupDetails(id: string) {
      return this.http.get('http://localhost:2019/GetGroupDetails/' + id);
    }

}

调用服务的Group-details.component代码

@Component({
  selector: 'ngx-group-details',
  templateUrl: './group-details.component.html',
  styleUrls: ['./group-details.component.scss']
})
export class GroupDetailsComponent implements OnInit {

  groupDetails;
  groupDetails2 = "NABEI";

  constructor(private _groupsService: GroupsService,
              private route: ActivatedRoute) { }

  ngOnInit() {

    let id = this.route.snapshot.paramMap.get("id");
    console.log("details: " + id);

    this._groupsService.GetGroupDetails(id).subscribe(data => this.groupDetails = data);
    console.log(this.groupDetails);
    // console.log("Details: " + JSON.stringify(this.groupDetails));
    // this.groupDetails = JSON.parse(this.groupDetails);
    // this._groupsService.GetGroups().subscribe(data => this.groupDetails = data);
    // console.log("Details" + this.groupDetails);

  }

}

这是来自MongoDB的数据

[
    {
        "_id": "5c35a1da1c9d4400005c7627",
        "groupID": "2",
        "userID": [
            "2"
        ],
        "groupTitle": "Year 1 Students",
        "expiryDate": "2030-01-01T00:00:00.000Z",
        "editable": false
    },
    {
        "_id": "5c3c2ea1932441118cee058c",
        "groupID": "1",
        "userID": [
        "3"
    ],
        "groupTitle": "Year 2 Students",
        "expiryDate": "2020-01-01T00:00:00.000Z",
        "editable": true
    },
    {
        "_id": "5c4b44dc1c9d4400002081db",
        "groupID": "3",
        "userID": [
            "1",
            "4"
    ],
        "groupTitle": "Year 3 Students",
        "expiryDate": "2020-01-01T00:00:00.000Z",
        "editable": false
    },
    {
        "_id": "5c4d84701c9d440000b2881a",
        "groupID": "4",
        "userID": [
            ""
        ],
        "groupTitle": "DIT Students",
        "expiryDate": "2030-01-01T00:00:00.000Z",
        "editable": true
    }
]

我想获取某个组的用户ID。例如,我需要groupID为3的group的UserID,我希望能够在group-details.component中获得1,4。

0 个答案:

没有答案