如何在Angular6 App中使用c8yClient代码(typescript文件)
How to use c8yClient code in the Angular 6 App (typescript file)
例如:
import { Client } from '@c8y/client';
const baseUrl = 'https://demos.cumulocity.com/';
const tenant = 'demos';
const user = 'user';
const password = 'pw';
(async () => {
const client = await Client.authenticate({
tenant,
user,
password
}), baseUrl);
const { data, paging } = await client.inventory.list();
// data = first page of inventory
const nextPage = await paging.next();
// nextPage.data = second page of inventory
})();
考虑到我在 angular 6 应用程序中有登录模块。如何使用上面的代码并在 login.component.ts 文件中对用户进行身份验证?
Cumulocity 发布了 demo on Stackblitz 如何登录用户。基本上,您使用用户名、密码和租户构建一个 ngForm
,并将其传递给 Cumulocity 客户端:
async login() {
const client = new Client(new BasicAuth(
{
user: this.model.user,
password: this.model.password,
tenant: this.model.tenant
}),
`https://${this.model.tenant}.cumulocity.com`
);
try {
let user = await client.user.current();
this.cumulocity.client = client;
} catch (ex) {
this.cumulocity.client = null;
this.error.shown = true;
this.error.msg = ex.message;
}
}
在这种情况下,this.model
是来自 ngFrom
的数据,单击按钮时会执行 login()?
函数。 this.cumulocity
变量包含一项服务,以便您可以与其他组件共享登录的客户端。
Note: If you run this on a different server (not hosted), then you need to enable CORS in the Cumulocity administration.
例如:
import { Client } from '@c8y/client';
const baseUrl = 'https://demos.cumulocity.com/';
const tenant = 'demos';
const user = 'user';
const password = 'pw';
(async () => {
const client = await Client.authenticate({
tenant,
user,
password
}), baseUrl);
const { data, paging } = await client.inventory.list();
// data = first page of inventory
const nextPage = await paging.next();
// nextPage.data = second page of inventory
})();
考虑到我在 angular 6 应用程序中有登录模块。如何使用上面的代码并在 login.component.ts 文件中对用户进行身份验证?
Cumulocity 发布了 demo on Stackblitz 如何登录用户。基本上,您使用用户名、密码和租户构建一个 ngForm
,并将其传递给 Cumulocity 客户端:
async login() {
const client = new Client(new BasicAuth(
{
user: this.model.user,
password: this.model.password,
tenant: this.model.tenant
}),
`https://${this.model.tenant}.cumulocity.com`
);
try {
let user = await client.user.current();
this.cumulocity.client = client;
} catch (ex) {
this.cumulocity.client = null;
this.error.shown = true;
this.error.msg = ex.message;
}
}
在这种情况下,this.model
是来自 ngFrom
的数据,单击按钮时会执行 login()?
函数。 this.cumulocity
变量包含一项服务,以便您可以与其他组件共享登录的客户端。
Note: If you run this on a different server (not hosted), then you need to enable CORS in the Cumulocity administration.