ts-basic-components-plugincomponent.md 11.4 KB
Newer Older
Z
zengyawen 已提交
1 2
# PluginComponent

E
ester.zhou 已提交
3
**\<PluginComponent>** allows the UI provided by an external application to be displayed in the application.
Z
zengyawen 已提交
4

5
> **NOTE**
E
ester.zhou 已提交
6
> - This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
Z
zengyawen 已提交
7
> 
E
ester.zhou 已提交
8
> - The APIs provided by this module are system APIs.
Z
zengyawen 已提交
9 10 11 12 13 14 15 16 17


## Required Permissions

None


## Child Components

E
ester.zhou 已提交
18
Not supported
Z
zengyawen 已提交
19 20 21 22 23 24 25 26 27


## APIs

PluginComponent(value: { template: PluginComponentTemplate, data: any })

Creates a **PluginComponent** to display the UI provided by an external application.

- Parameters
28
  | Name | Type | Mandatory | Default Value | Description |
Z
zengyawen 已提交
29
  | -------- | -------- | -------- | -------- | -------- |
E
esterzhou 已提交
30
  | value | {<br/>template: PluginComponentTemplate,<br/>data: KVObject<br/>} | Yes | - | **template**: template of the **PluginComponent**, which is bound to the component defined by the provider.<br/>**data**: data passed to the **PluginComponent** provider. |
Z
zengyawen 已提交
31

E
ester.zhou 已提交
32 33
- PluginComponentTemplate
  | Name | Type | Description |
Z
zengyawen 已提交
34
  | -------- | -------- | -------- |
E
ester.zhou 已提交
35 36
  | source | string | Component template name. |
  | ability | string | Name of the provider ability. |
Z
zengyawen 已提交
37 38 39 40


## Events

E
ester.zhou 已提交
41
| Name | Description |
Z
zengyawen 已提交
42
| -------- | -------- |
E
ester.zhou 已提交
43 44
| onComplete(callback: () =&gt; void) | Triggered when the component loading is complete. |
| onError(callback: (info: { errcode: number, msg: string }) =&gt; void) | Triggered when an error occurs during component loading.<br/>**errcode**: error code.<br/>**msg**: error information. |
Z
zengyawen 已提交
45 46 47 48


## PluginComponentManager

E
ester.zhou 已提交
49
Provides APIs for the **PluginComponent** user to request the component and data and for the **PluginComponent** provider to push component templates and data.
Z
zengyawen 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63


## Modules to Import


```
import pluginComponentManager from '@ohos.plugincomponent'
```


## push

push(param: PushParameters, callback: AsyncCallback&lt;void&gt;): void

E
ester.zhou 已提交
64
Used by the component provider to push a component and data to the component user.
Z
zengyawen 已提交
65 66 67


- Parameters
68
  | Name | Type | Mandatory | Description |
Z
zengyawen 已提交
69
  | -------- | -------- | -------- | -------- |
E
ester.zhou 已提交
70
  | param | PushParameters | Yes | Information about the component user. For details, see **PushParameters**. |
E
esterzhou 已提交
71
  | callback | AsyncCallback&lt;void&gt; | Yes | Asynchronous callback used to return the result. |
Z
zengyawen 已提交
72

E
ester.zhou 已提交
73
- PushParameters
74
  | Name | Type | Mandatory | Description |
Z
zengyawen 已提交
75
  | -------- | -------- | -------- | -------- |
E
ester.zhou 已提交
76
  | want | Want | Yes | Ability information of the component user. |
E
esterzhou 已提交
77 78 79
  | name | string | Yes | Component name. |
  | data | KVObject | No | Component data value. |
  | extraData | KVObject | No | Additional data value. |
Z
zengyawen 已提交
80

E
ester.zhou 已提交
81 82 83
- Example

  See [PluginComponent Provider](#plugincomponent-provider)
Z
zengyawen 已提交
84 85 86 87 88 89


## request

request(param: RequestParameters, callback: AsyncCallback&lt;RequestCallbackParameters&gt;): void

E
ester.zhou 已提交
90
Used by the component user to request a component from the component provider.
Z
zengyawen 已提交
91 92

- Parameters
93
  | Name | Type | Mandatory | Description |
Z
zengyawen 已提交
94
  | -------- | -------- | -------- | -------- |
E
ester.zhou 已提交
95
  | param | RequestParameters | Yes | Information about the component request. For details, see  **RequestParameters**. |
E
esterzhou 已提交
96
  | callback | AsyncCallback<RequestCallbackParameters \| void&gt; |  | Asynchronous callback used to return the requested data. |
Z
zengyawen 已提交
97

E
ester.zhou 已提交
98
- RequestParameters
99
  | Name | Type | Mandatory | Description |
Z
zengyawen 已提交
100
  | -------- | -------- | -------- | -------- |
E
esterzhou 已提交
101 102 103
  | want | Want     | Yes | Ability information of the component provider. |
  | name | string | Yes | Name of the requested component. |
  | data | KVObject | Yes | Additional data. |
Z
zengyawen 已提交
104

E
ester.zhou 已提交
105
- RequestCallbackParameters
106
  | Name | Type | Description |
Z
zengyawen 已提交
107
  | -------- | -------- | -------- |
E
esterzhou 已提交
108 109 110
  | componentTemplate | PluginComponentTemplate | Component template. |
  | data | KVObject | Component data. |
  | extraData | KVObject | Additional data. |
Z
zengyawen 已提交
111

E
ester.zhou 已提交
112 113
- KVObject
  | Name | Type | Description |
Z
zengyawen 已提交
114
  | -------- | -------- | -------- |
E
ester.zhou 已提交
115
  | key | number \| string \| boolean \| Array \| KVObject | **KVObject** uses **key** and **value** to store data. **key** is of the string type, and **value** can be of the number, string, boolean, array type or another **KVObject**. |
Z
zengyawen 已提交
116 117


E
ester.zhou 已提交
118 119 120
- Example

  See [PluginComponent User](#plugincomponent-user).
Z
zengyawen 已提交
121 122 123 124 125 126 127 128 129


## on

on(eventType: string, callback: OnPushEventCallback | OnRequestEventCallback): void

Listens for events of the request type and returns the requested data, or listens for events of the push type and receives the data pushed by the provider.

- Parameters
130
  | Name | Type | Mandatory | Description |
Z
zengyawen 已提交
131
  | -------- | -------- | -------- | -------- |
E
ester.zhou 已提交
132
  | eventType | string | Yes | Type of the event to listen for. The options are **"push"** and **"request"**.<br/>**"push"**: The component provider pushes data to the component user.<br/>**"request"**: The component user proactively requests data from the component provider. |
E
esterzhou 已提交
133
  | callback | OnPushEventCallback \| OnRequestEventCallback | Yes | Callback used to return the result. For details, see description of callback. |
Z
zengyawen 已提交
134

E
ester.zhou 已提交
135
- callback
136
  | Name | Type | Description |
Z
zengyawen 已提交
137
  | -------- | -------- | -------- |
E
esterzhou 已提交
138 139
  | OnRequestEventCallback | (source: Want,<br/>name: string,<br/>data: KVObject ) =>RequestEventResult | Callback for the data request event.<br/>**source**: ability information of the component requester.<br/>**name**: name of the requested component.<br/>**data**: additional data.<br/>Return value: request data and result. |
  | OnPushEventCallback | (source: Want,<br/>template: PluginComponentTemplate,<br/>data: KVObject,<br/>extraData: KVObject<br/>) =&gt; void | Callback used to receive the data pushed by the component provider.<br/>**source**: ability information of the component provider.<br/>**template**: component template.<br/>**data**: component update data.<br/>**extraData**: additional data. |
Z
zengyawen 已提交
140

E
ester.zhou 已提交
141
- RequestEventResult
142
  | Name | Type | Description |
Z
zengyawen 已提交
143
  | -------- | -------- | -------- |
E
esterzhou 已提交
144 145 146
  | template | string | Component name. |
  | data | KVObject | Component data. |
  | extraData | KVObject | Additional data. |
Z
zengyawen 已提交
147

E
ester.zhou 已提交
148
- Example
Z
zengyawen 已提交
149

E
ester.zhou 已提交
150
  See [PluginComponent Tools](#plugincomponent-tools).
Z
zengyawen 已提交
151 152 153 154

## Example


E
ester.zhou 已提交
155
### PluginComponent User
Z
zengyawen 已提交
156 157


E
ester.zhou 已提交
158 159 160
```ts
//PluginUserExample.ets
import plugin from "plugin_component.js"
Z
zengyawen 已提交
161 162 163

@Entry
@Component
E
ester.zhou 已提交
164
struct PluginUserExample {
Z
zengyawen 已提交
165 166 167 168 169 170 171 172 173 174
  @StorageLink("plugincount") plugincount: Object[] = [
    { source: 'plugincomponent1', ability: 'com.example.plugin' },
    { source: 'plugintemplate', ability: 'com.example.myapplication' },
    { source: 'plugintemplate', ability: 'com.example.myapplication' }]

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Text('Hello World')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
E
ester.zhou 已提交
175 176
      Button('Register Request Listener')
        .fontSize(30)
Z
zengyawen 已提交
177 178
        .width(400)
        .height(100)
E
ester.zhou 已提交
179 180 181 182
        .margin({top:20})
        .onClick(()=>{
          plugin.onListener()
          console.log("Button('Register Request Listener')")
Z
zengyawen 已提交
183
        })
E
ester.zhou 已提交
184
      Button('Request')
Z
zengyawen 已提交
185 186 187 188 189
        .fontSize(50)
        .width(400)
        .height(100)
        .margin({ top: 20 })
        .onClick(() => {
E
ester.zhou 已提交
190 191
          plugin.Request()
          console.log("Button('Request')")
Z
zengyawen 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
        })
      ForEach(this.plugincount, item => {
        PluginComponent({
          template: { source: 'plugincomponent1', ability: 'com.example.plugin' },
          data: { 'countDownStartValue': 'new countDownStartValue' }
        }).size({ width: 500, height: 100 })
          .onComplete(() => {
            console.log("onComplete")
          })
          .onError(({errcode, msg}) => {
            console.log("onComplete" + errcode + ":" + msg)
          })
      })
    }
    .width('100%')
    .height('100%')
E
ester.zhou 已提交
208
  }
Z
zengyawen 已提交
209 210 211
}
```

E
ester.zhou 已提交
212
### PluginComponent Provider
Z
zengyawen 已提交
213

E
ester.zhou 已提交
214 215 216
```ts
//PluginProviderExample.ets
import plugin from "plugin_component.js"
Z
zengyawen 已提交
217

E
ester.zhou 已提交
218 219 220 221
@Entry
@Component
struct PluginProviderExample {
  @State message: string = 'no click!'
Z
zengyawen 已提交
222

E
ester.zhou 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Button('Register Push Listener')
        .fontSize(30)
        .width(400)
        .height(100)
        .margin({top:20})
        .onClick(()=>{
          plugin.onListener()
          console.log("Button('Register Push Listener')")
        })
      Button('Push')
        .fontSize(30)
        .width(400)
        .height(100)
        .margin({top:20})
        .onClick(()=>{
          plugin.Push()
          this.message = "Button('Push')"
          console.log("Button('Push')")
        })
      Text(this.message)
        .height(150)
        .fontSize(30)
        .padding(5)
        .margin(5)
    }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 })
  }
}
Z
zengyawen 已提交
252
```
E
ester.zhou 已提交
253 254 255 256 257 258 259

### PluginComponent Tools


```js
//plugin_component.js
import pluginComponentManager from '@ohos.pluginComponent'
Z
zengyawen 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

function onPushListener(source, template, data, extraData) {
  console.log("onPushListener template.source=" + template.source)
  var jsonObject = JSON.parse(data.componentTemplate.source)
  console.log("request_callback1:source json object" + jsonObject)
  var jsonArry = jsonObject.ExternalComponent
  for (var i in jsonArry) {
    console.log(jsonArry[i])
  }
  console.log("onPushListener:source json object" + jsonObject)
  console.log("onPushListener:source json string" + JSON.stringify(jsonObject))
  console.log("onPushListener template.ability=" + template.ability)
  console.log("onPushListener data=" + JSON.stringify(data))
  console.log("onPushListener extraData=" + JSON.stringify(extraData))
}

E
ester.zhou 已提交
276 277 278 279 280 281 282
function onRequestListener(source, name, data)
{
    console.log("onRequestListener name=" + name);
    console.log("onRequestListener data=" + JSON.stringify(data));
    return {template:"plugintemplate", data:data};
}

Z
zengyawen 已提交
283 284 285 286
export default {
  //register listener
  onListener() {
    pluginComponentManager.on("push", onPushListener)
E
ester.zhou 已提交
287
    pluginComponentManager.on("request", onRequestListener)
Z
zengyawen 已提交
288
  },
E
ester.zhou 已提交
289 290 291 292
  Push() {
    // The component provider pushes data.
    pluginComponentManager.push(
      {
Z
zengyawen 已提交
293 294 295 296 297 298 299 300 301
        want: {
          bundleName: "com.example.myapplication",
          abilityName: "com.example.myapplication.MainAbility",
        },
        name: "plugintemplate",
        data: {
          "key_1": "plugin component test",
          "key_2": 34234
        },
E
ester.zhou 已提交
302 303 304 305
        extraData: {
          "extra_str": "this is push event"
        },
        jsonPath: "",
Z
zengyawen 已提交
306 307
      },
      (err, data) => {
E
ester.zhou 已提交
308
        console.log("push_callback: push ok!");
Z
zengyawen 已提交
309 310 311
      }
    )
  },
E
ester.zhou 已提交
312 313 314
  Request() {
    // The component user proactively sends data.
    pluginComponentManager.request({
Z
zengyawen 已提交
315 316 317 318 319 320 321 322 323
        want: {
          bundleName: "com.example.myapplication",
          abilityName: "com.example.myapplication.MainAbility",
        },
        name: "plugintemplate",
        data: {
          "key_1": "plugin component test",
          "key_2": 34234
        },
E
ester.zhou 已提交
324
        jsonPath: "",
Z
zengyawen 已提交
325 326
      },
      (err, data) => {
E
ester.zhou 已提交
327 328 329 330 331 332 333 334 335 336 337
        console.log("request_callback: componentTemplate.ability=" + data.componentTemplate.ability)
        console.log("request_callback: componentTemplate.source=" + data.componentTemplate.source)
        var jsonObject = JSON.parse(data.componentTemplate.source)
        console.log("request_callback:source json object" + jsonObject)
        var jsonArry = jsonObject.ExternalComponent
        for (var i in jsonArry) {
          console.log(jsonArry[i])
        }
        console.log("request_callback:source json string" + JSON.stringify(jsonObject))
        console.log("request_callback: data=" + JSON.stringify(data.data))
        console.log("request_callback: extraData=" + JSON.stringify(data.extraData))
Z
zengyawen 已提交
338 339
      }
    )
E
ester.zhou 已提交
340
  }
Z
zengyawen 已提交
341 342
}
```